Nodejs Express框架缓存 [英] Nodejs Express framework caching
问题描述
在配置文件中我有
app.configure('production',function(){
var oneYear = 31557600000;
app.use(express.static(__ dirname +'/ public' ,{maxAge:oneYear}));
app.use(express.errorHandler());});
我使用以下命令运行应用程序:
$ NODE_ENV =生产节点app.js
,文件(图像,css,js)似乎没有缓存,它们总是作为新文件。
P / s:我刚刚用localhost测试,缓存似乎在本地主机上工作,但是,当上传到服务器时,缓存不再工作。
Express是建立在Connect上的,Connect提供了静态中间件。这是缓存下的代码:
if(!res.getHeader('Cache-Control'))res。 setHeader('Cache-Control','public,max-age ='+(maxAge / 1000));
你可以在这里找到代码:
https://github.com/senchalabs/connect/ blob / master / lib / middleware / static.js#L147
所以你可以看到Express正在向浏览器发送一个Cache-Control头告诉他缓存该文件一段时间。所以这不是一个加载一个文件,然后总是服务于所有的客户端,但更多的是告诉每个客户端首次下载它缓存文件(这意味着所有的客户端都必须下载该文件在它们被缓存之前曾经有一次)。
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.
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).
这篇关于Nodejs Express框架缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!