Reputation: 2372
The nodejs documentation says
Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.
But it does not specify the scope. Are loaded modules cached for multiple calls to require('module') in the current HTTP request or across multiple HTTP requests?
Upvotes: 1
Views: 1591
Reputation: 3422
Yes, they are.
Unlike other common server environments, like PHP, a node.js server will not shut down after a request is done.
Suppose you are using the excellent express framework, maybe this example will help to understand the difference:
... // setup your server
// do a route, that will show a call-counter
var callCount = {};
app.get('/hello/:name', function(request, response) {
var name = request.params.name;
callCount[name] = (callCount[name] || 0) + 1
response.send(
"Hello " + name + ", you invoked this " + callCount[name] + " times");
});
});
When calling curl localhost:3000/hello/Dave
you will receive a higher number with every subsequent call.
1st call: Hello Dave, you invoked this 1 times
2nd call: Hello Dave, you invoked this 2 times
... and so on ...
So your callCount
will be modified by any request to that route. It does not matter where it comes from, and it could be defined in any module you're require
ing.
Anyway, those variables, defined in any module, will be reset when the server restarts. You can counter that by putting them into a Store, that is separated from you node.js process, like a Redis Store (see node-redis), a file on your file-system or a database, like MongoDB. In the end it's up to you. You just need to be aware of where your data comes from and goes to.
Hope that helps.
Upvotes: 3
Reputation: 12645
Yes. Also from the docs:
Multiple calls to require('foo') may not cause the module code to be executed
multiple times. This is an important feature. With it, "partially done"
objects can be returned, thus allowing transitive dependencies to be loaded
even when they would cause cycles. If you want to have a module execute code
multiple times, then export a function, and call that function.
Upvotes: 0