缓存

2017-12-10  本文已影响23人  辉夜乀

缓存

image.png

创建模块 cache.js

// cache.js

const {cache} = require('../config/defaultConfig');

function refreshRes(stats, res) {
  const {maxAge, expires, cacheControl, lastModified, etag} = cache;

  if (expires) {
    res.setHeader('Expires', new Date((Date.now() + maxAge * 1000)).toUTCString());
  }

  if (cacheControl) {
    res.setHeader('Cache-Control', `public, max-age=${maxAge}`);
  }

  if (lastModified) {
    res.setHeader('Last-Modified', stats.mtime.toUTCString());
  }

  if (etag) {
    res.setHeader('ETag', `${stats.size}-${stats.mtime}`);
  }
}

module.exports = function isFresh(stats, req, res) {
  refreshRes(stats, res);

  const lastModified = req.headers['if-modified-since'];
  const etag = req.headers['if-none-match'];

  /*如果是第一次请求,没有 lastModified 和 etag*/
  if (!lastModified && !etag) {
    return false;
  }

  /*如果有 lastModified 但是和原来的不一样*/
  else if (lastModified && lastModified !== res.getHeader('Last-Modified')) {
    return false;
  }

  /*如果有 etag 但是和原来的不一样*/
  else if (etag && etag !== res.getHeader('ETag')) {
    return false;
  }

  return true;

};

defaultConfig.js 模块中添加 cache 属性

const defaultConfig = {
  root: process.cwd(),
  hostname: '127.0.0.1',
  port: 9527,
  compressType: /\.(html|css|js|md|json|jpg|jpeg|png)$/,
  cache: {      //添加 cache 属性
    maxAge: 600,
    expires: true,
    cacheControl: true,
    lastModified: true,
    etag: true
  }
};

module.exports = defaultConfig;

route.js 中引用

const isFresh = require('./cache');

    /*判断 res 是否新鲜,如果新鲜则返回 304*/
if (isFresh(stats, req, res)) {
    res.statusCode = 304;
    res.end();
    return;
}

浏览器再次访问 url 可以看到 304 状态码。

image.png
上一篇 下一篇

猜你喜欢

热点阅读