引入
浏览器解析页面的大致流程如下:
如果文件过大从webserver到浏览器的传输时间就会很长,所以我们可以先将文件压缩成gzip
文件再进行传输。
压缩成gzip文件方法就是包含在zlib模块中。
使用
在服务器上进行文件压缩之后传回页面上
const http = require("http")
const fs = require("fs")
const zlib = require("zlib")
const gzip = zlib.createGzip()
http.createServer((req, res) => {
const readStream = fs.createReadStream("./index.js")
res.writeHead(200, { "Content-Type": "application/x-javascript;charset=utf-8","Content-Encoding":"gzip"})
readStream.pipe(gzip).pipe(res)
}).listen(3001, () => {
console.log("服务器启动")
})
不使用gzip压缩之前文件大小是:
使用gzip压缩之后文件大小是: