简体   繁体   English

如何在不导致磁盘读取的情况下提供静态文件?

[英]How to serve a static file without causing a disk read?

res.sendFile is the recommended way to send a static file using . res.sendFile是使用发送静态文件的推荐方式。 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 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假设确实读取每个请求(很难确认,因为它可能使用了一个巧妙的缓存,利用fs.watchfs.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.

相关问题 如何使用服务 static 文件与快递和反应? - how to use serve static file with express and react? Webpack:如何使用 webpack-dev-server 编译、写入磁盘和提供静态内容 (js/css) - Webpack: How to compile, write on disk and serve static content (js/css) using webpack-dev-server 如何在不使用布局的情况下使用html文件提供和浏览静态文件夹 - How to serve and browse static folder with html files without using layout 如何在不使用Asset Pipeline的情况下在Rails 5中提供静态图像? - How to serve static image in Rails 5 without using Asset Pipeline? 如何提供静态文件并将其路径提供给一个用户? - How to serve static file and give its path to one user? 如何在 Express JS 的所有路由上使用 static 资源提供文件? - How to serve file with static resources on all routes in Express JS? 如何使用Node Express提供静态文件? - How do I serve a static file using Node Express? Webpack开发服务器-如何为具有更新资产的静态文件提供服务? - Webpack dev-server - how to serve a static file with updated assets? 我怎样才能适当地提供与 flask 集成的 static js 文件? - How can i appropriately serve a static js file integrated with flask? 如何在不暴露完整的“/static”文件夹的情况下在 express 中提供单个静态文件? - How to serve singular static files in express without exposing full '/static' folder?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM