如何在内存中缓存使用 express.static 提供的文件?

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.static 和 res.sendFile 提供的文件在内存中?

简短的回答是你不能,至少不能 express.static()。您将需要使用第三方模块或编写自己的模块。此外,您可以在适当的问题跟踪器上打开一个功能请求问题,要求使用某种挂钩来拦截调用以从磁盘读取请求的文件。

这通常是不值得的,因为操作系统会为您解决这个问题。

所有现代操作系统都将使用未使用的 RAM 作为 "buffer cache" or "page cache"。最近使用的文件系统数据将存储在那里,在 RAM 中,因此一旦文件被加载到内存中,任何后续读取都将从内存中提供服务,而不是实际从磁盘读取。

依赖这个的好处是OS会在进程的内存消耗恰好增加时自动从缓冲区缓存中清除数据,因此没有运行风险使这些进程耗尽内存(就像您自己在用户 space 中实施某些操作时可能遇到的那样)。

一种方法是在 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();
});