[英]How to serve a static file without causing a disk read?
res.sendFile
is the recommended way to send a static file using express . res.sendFile
是使用express发送静态文件的推荐方式。 However, from what I can tell, res.sendFile
is reading file from the disk on every request, eg但是,据我所知,
res.sendFile
正在根据每个请求从磁盘读取文件,例如
router.get('/', (req, res) => {
res.sendFile('./guest.js');
});
Accessing /
will make a disk read on every request.访问
/
将对每个请求进行磁盘读取。
Assuming that express does indeed read on every request (it is hard to confirm, because it could be using a clever cache that utilises fs.watch
or fs.stat
to asses whether to read a new file), then a simple solution is to get the file's content into a variable and serve it using res.rend
, eg假设express确实读取每个请求(很难确认,因为它可能使用了一个巧妙的缓存,利用
fs.watch
或fs.stat
来评估是否读取新文件),那么一个简单的解决方案是获取文件的内容变成一个变量并使用res.rend
提供它,例如
const guestScript = fs.readFileSync('./guest.js', 'utf-8');
router.get('/', (req, res) => {
res
.set('Content-Type', 'application/javascript')
.send(guestScript);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.