I've done some reading on JavaScript memory management in the past, and am aware of the issue with circular DOM references, etc.
However I'm still a little bit uncomfortable as this translates to a server-side JavaScript environment such as node.js, and more specifically an API written on express.
var npm_moduleA = require('npmA')({ someInitArg : 'blah' }),
app = express.createServer();
app.get('/api/foo', function (req, res) {
var result = npm_moduleA.doSomething();
res.send(result);
});
app.get('/api/bar', function (req, res) {
var npm_moduleB = require('npmB')({ someInitArg : 'blah' }),
result = npm_moduleB.doSomethingElse();
res.send(result);
});
What is the lifecycle of npm_moduleA
? It gets created at the moment that the server starts, but when (if at all does GC kick in against it) - I'm guessing that it never gets touched because its in the global scope?
In '/api/bar/', should npm_moduleB
be deleted after each request? Or should this be left to the GC alone.
Is the global instantiation of npm_moduleA
significantly more efficient than repetative the instantiation (and possible deletion) of npm_moduleB
?
Avoid Accidental Globals This could be the result of a typo and could lead to a memory leak. Another way could be when assigning a variable to this within a function in the global scope. To avoid issues like this, always write JavaScript in strict mode using the 'use strict'; annotation at the top of your JS file.
JavaScript heap out of memory - how to increase the max memory for Node with max_old_space_size. If you want to increase the max memory for Node you can use --max_old_space_size option. You should set this with NODE_OPTIONS environment variable.
Node. js is a runtime environment to allow JavaScript to not only be run in the browser, but also on the server (or almost any environment, really). That also expanded the types of applications that could be built with the language since it wasn't tied to only the client-side anymore.
As the node.js won't create and destroy running context for each call, so both npm_moduleA
and npm_moduleB
will live (in cache) until you kill the server.
In fact no matter where you require the module, it just get a pointer to the module's entry point. it doesn't instance any thing at run time.
here is a example:
index.js
var t = require('./module.js');
t.value = 10;
function test() {
var t2 = require('./module.js');
console.log(t2.value);
}
test();
module.js
module.exports = {};
console outputs:
10
In this case just put your require()s at global scope for once. don't do requires in callbacks, because require() has some file name resolving work to do, and it has no difference from require in global scope (in any aspect.)
But if you are going to instance a class new SomeClass()
, then where you do it matters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With