如何缓存视图以便文件不需要 re-read 和 re-rendered

How to cache views so files don't need to be re-read and re-rendered

我有这些视图渲染调用:

router.get('/mcn', (req, res) => {
  res.render('product/mcn', { layout: 'product/layout', contactKey: 'mcn' });
});

router.get('/agency', (req, res) => {
  res.render('product/agency', { layout: 'product/layout', contactKey: 'agency' });
});

router.get('/esports', (req, res) => {
  res.render('product/esports', { layout: 'product/layout', contactKey: 'esports' });
});

router.get('/brand', (req, res) => {
  res.render('product/brand', { layout: 'product/layout', contactKey: 'brand' });
});

router.get('/analytics', (req, res) => {
  res.render('product/analytics', { layout: 'product/layout', contactKey: 'analytics' });
});

router.get('/rightsmanagement', (req, res) => {
  res.render('product/content-id', { layout: 'product/layout', contactKey: 'content-id' });
});

您可能会注意到 - 没有传递动态数据。所以我想知道如何缓存这些视图?像这样:

const pug = require('pug');

 {
    const templateStr = fs.readFileSync(path.resolve(__dirname +'/../views/product/content-id'));

    const fn = pug.compile(templateStr, {});

    const html = fn({ layout: 'product/layout', contactKey: 'content-id' });

    router.get('/rightsmanagement', (req, res) => {
      res.send(html);
    });

  }

这样对吗?我想我缺少一些 headers?没有人知道正确的 headers 是什么吗?

我不确定你用 pug.compile() 做什么,但是你可以使用 Cache-Control header 和 max-age 值来告诉浏览器缓存您发送的任何内容:

router.get('/rightsmanagement', (req, res) => {
  // set max-age to whatever you think is best
  res.set('Cache-Control', 'max-age=31536000');
  res.send(html);
});

您可以将其用作设置渲染的中间件,因为 req.path 在您的处理程序中包含唯一的动态内容,rightsmanagment 路由的特殊情况除外:

const renderCacheView = (req, res, next) => {
  let path = req.path;
  if (path === 'rightsmanagement') path = 'content-id';
  // set max-age to whatever you think is best
  res.set('Cache-Control', 'max-age=31536000');
  res.render(`product/${path}`, { layout: 'product/layout', contactKey: path});
};

我认为您甚至可以通过使用正则表达式作为路径来传递这一事实而无需编写这么多路由:

router.get(/mcn|agency|esports|brand|analytics|rightsmanagement/, renderCacheView);