node.js express.static() 是否在内存中缓存文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32154656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does express.static() cache files in the memory?
提问by Chong Lip Phang
In ExpressJS for NodeJS, we can do the following:
在 ExpressJS for NodeJS 中,我们可以执行以下操作:
app.use(express.static(__dirname + '/public'));
to serve all the static CSS, JS, and image files. My questions are these:
为所有静态 CSS、JS 和图像文件提供服务。我的问题是这些:
1) When we do that, does Express automatically cache the files in the server's memory or does it read from the hard disk every time one of the resources is served?
1) 当我们这样做时,Express 是自动将文件缓存在服务器的内存中还是每次提供一个资源时从硬盘读取?
2) When we do that, does Express, using ETag by default, save the resources on the client's hard disk, or on the client's memory only?
2)当我们这样做时,默认使用ETag的Express是将资源保存在客户端的硬盘上,还是只保存在客户端的内存上?
回答by Alexander Korzhykov
- The static middleware does no server-side caching. It lets you do two methods of client-side caching: ETag and Max-Age:
- 静态中间件没有服务器端缓存。它允许您执行两种客户端缓存方法:ETag 和 Max-Age:
If the browser sees the ETagwith the page, it will cache it. The next time the browser loads the page it checks for the ETag number changes. If the file is exactly the same, and so is its ETag - the server responds with an HTTP 304("not modified") status code instead of sending all the bytes again and saves a bunch of bandwidth. Etag is turned-on by default but you can turn it off like this:
如果浏览器看到带有页面的ETag,它将缓存它。下次浏览器加载页面时,它会检查 ETag 编号是否发生变化。如果文件完全相同,它的 ETag 也完全相同 - 服务器以 HTTP 304(“未修改”)状态代码进行响应,而不是再次发送所有字节并节省大量带宽。默认情况下 Etag 是打开的,但您可以像这样关闭它:
app.use(express.static(myStaticPath, {
etag: false
}))
Max-ageis will set the max-age to some amount of time so the browser will only request that resource after one day has passed.
Max-age会将 max-age 设置为一定的时间,因此浏览器只会在一天过去后请求该资源。
app.use(express.static(myStaticPath, {
maxAge: '5000' // uses milliseconds per docs
}))
For more details you can read this article
有关更多详细信息,您可以阅读这篇文章
- By default it's on the hard-drive, but someone can use something like this
- 默认情况下,它的硬盘驱动器上,但有人可以使用类似于此

