node实现Etag和cache-control缓存

598 阅读1分钟

`

1.ETag


const app = require('express')()
const fs = require('fs')
const crypto = require('crypto')
//这个函数可以根据文件内容生成独有hash
const getHash = function (str) {
    var shasum = crypto.createHash('sha1');
    return shasum.update(str).digest('base64');
}
app.get('/aa.css', (req, res) => {
    const content = fs.readFileSync('./static-server/aa.css')
    const hash = getHash(content)
    const noneMatch = req.headers['if-none-match']
    if (hash === noneMatch) {
        res.writeHead(304, 'Not Modified')
        res.end()
    } else {
    //第一次请求会进入这里
    //这里响应头带上ETag后,下次游览器请求头上就会带上if-none-match了
        res.setHeader('ETag', hash)
        res.setHeader('Content-Type', 'text/css')
        res.writeHead(200, 'ok')
        res.write(content)
        res.end()
    }
})
app.listen(3000)

2.cache-control

    res.setHeader('Cache-Control', 'max-age=' + 10 * 365 * 24 * 60 * 60 * 1000)