Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Express framework caching

Tags:

I am using Nodejs and Express Js. Also I add NowJS to the Express Js to do some real-time stuffs.

In the configuration file I have

app.configure('production', function() { var oneYear = 31557600000; app.use(express.static(__dirname + '/public', { maxAge: oneYear })); app.use(express.errorHandler());}); 

And I run the application using this command:

$ NODE_ENV=production node app.js 

However, the files(images, css, js) seem not to be cached, they are always served as new file.

P/s: I have just tested it with localhost, the cache seems to work on localhost, however, when uploading to the server, the cache is not working anymore.

like image 212
Tan Nguyen Avatar asked Oct 17 '11 07:10

Tan Nguyen


People also ask

Does Express have caching?

It'll basically look for a cached value using the request's URL as the key. If it is found, it is sent directly as the response. If it's currently not cached, it'll wrap Express's send function to cache the response before actually sending it to the client and then calling the next middleware.

How do I enable caching in node JS?

Implement caching with following approach: On API request, check if the cache has key already set using has(key) function. If the cache has the key, retrieve the cached value by get(key) function and use it instead of performing operation again. (This saves time)


2 Answers

Express is built on Connect, and Connect provides the "static" middleware. Here's the code under the hood for the caching:

if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + (maxAge / 1000)); 

You can find that code here:

https://github.com/senchalabs/connect/blob/master/lib/middleware/static.js#L147

So as you can see Express is sending a "Cache-Control" header to the browser, telling him to cache that file for a period. So this isn't a "load a file once and then always serve it to all clients", but more of a "tell each client to cache the file the first time he downloads it" (which means all the clients will have to download that file once before it's cached for them).

like image 61
alessioalex Avatar answered Oct 07 '22 11:10

alessioalex


The following code does the job:

app.use(function (req, res, next) {     if (req.url.match(/^\/(css|js|img|font)\/.+/)) {         res.setHeader('Cache-Control', 'public, max-age=3600'); // cache header     }     next(); }); 
like image 22
Felix Avatar answered Oct 07 '22 11:10

Felix