Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

node.js - Nodejs Express framework caching

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...