1

文件目录

clipboard.png

文件内容

server3.js
const http = require('http');
const fs = require('fs');
http.createServer(function(req, res) {
    console.log('request come', req.url);
    const html = fs.readFileSync('index.html', 'utf8');
    if (req.url === '/') {
        res.writeHead(200, {
            "Content-Type":"text/html"
        })
        res.end(html)   
    }
    if (req.url === '/script.js') {
        res.writeHead(200, {
            "Content-Type": "text/javascript",
            "Cache-Control":"max-age=20"
        })
        res.end('console.log("script loaded")')   
    }
}).listen(8888)
console.log('server start at port 8888')
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    8888
    <script src="/script.js"></script>
</body>
</html>

运行

第一次请求

clipboard.png

clipboard.png

第二次请求

clipboard.png

webpack打包的时候,js后面会增哈希字符串

  1. 在缓存时间段内,如果服务端的内容发生了变化,再次发起请求,还是会从本地缓存中读取,并不会从服务端重新请求
  2. 所以webpack打包的时候,会根据内容生成哈希字符串
server3.js
修改缓存最大时间,和打印内容
const http = require('http');
const fs = require('fs');
http.createServer(function(req, res) {
    console.log('request come', req.url);
    const html = fs.readFileSync('index.html', 'utf8');
    if (req.url === '/') {
        res.writeHead(200, {
            "Content-Type":"text/html"
        })
        res.end(html)   
    }
    if (req.url === '/script.js') {
        res.writeHead(200, {
            "Content-Type": "text/javascript",
            "Cache-Control":"max-age=200"
        })
        res.end('console.log("script loaded 222")')   
    }
}).listen(8888)
console.log('server start at port 8888')

在200秒内请求,还是会返回原来的内容

clipboard.png
超出200秒,会返回新的内容

clipboard.png


渣渣辉
1.3k 声望147 粉丝