[英]How do I cache files served with express.static in memory?
根據這個問題express.static 每次都從硬盤讀取文件。 我想將服務的文件緩存在內存中,因為它們不會改變,所以數量不多,而且我有足夠的內存可以這樣做。
所以對於這樣的代碼:
// serve all static files from the /public folder
app.use(express.static(path.join(__dirname, 'public')))
// serve index.html for all routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'))
})
如何確保 express 在內存中緩存通過 express.static 和 res.sendFile 提供的文件?
簡短的回答是你不能,至少不能用express.static()
。 您將需要使用第三方模塊或編寫自己的模塊。 此外,您可以在適當的問題跟蹤器上打開一個功能請求問題,要求某種掛鈎來攔截從磁盤讀取請求文件的調用。
這通常不值得麻煩,因為操作系統會為您處理這個問題。
所有現代操作系統都將使用未使用的 RAM 作為“緩沖區緩存”或“頁面緩存” 。 最近使用的文件系統數據將存儲在 RAM 中,因此一旦文件加載到內存中,任何后續讀取都將從內存中提供,而不是實際從磁盤讀取。
依賴於此的優點是,當進程的內存消耗增加時,操作系統會自動從緩沖區緩存中清除數據,因此不會冒內存耗盡這些進程的風險(正如您在實施時可能遇到的那樣)自己在用戶空間中的東西)。
一種方法是在 Node 啟動時讀取 HTML 文件並從變量提供 HTML 字符串。 這是一個使用 Express 的示例。 將 MY_DIST_FOLDER 替換為您的文件夾位置。
//using Express const fs = require('fs'); const express = require('express'); const app = express(); //get page HTML string function getAppHtml() { let html = ''; try { html = fs.readFileSync(`${MY_DIST_FOLDER}/index.html`, 'utf8'); } catch (err) { console.error(err); } return html; } let html = getAppHtml(); //serve dist folder catching all other urls app.get(/.*/, (req, res) => { if (html) { res.writeHead(200, {'Content-Type': 'text/html','Content-Length':html.length}); } else { html = "Node server couldn't find the index.html file. Check to see if you have built the dist folder."; res.writeHead(500, {'Content-Type': 'text/html','Content-Length':html.length}); } res.write(html); res.end(); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.