Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Are nodejs modules cached across multiple HTTP requests?

Are nodejs modules cached across multiple HTTP requests?

Problem

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?

Problem courtesy of: Rajiv

Solution

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 requireing.

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.

Solution courtesy of: Tharabas

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Are nodejs modules cached across multiple HTTP requests?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×