zilib
nodejs的zlib模块提供通过 Gzip、Deflate/Inflate、和 Brotli 实现的压缩功能。
未压缩前
const http = require('http')
const fs = require('fs')
const server = http.createServer()
server.on('request', (req, res) => {
console.log('request from', req.url)
const html = fs.readFileSync('index.html')
res.writeHead(200, {
'Content-Type': 'text/html',
})
res.end(html)
})
server.listen(3003, () => {
console.log('listen http://127.0.0.1:3003')
})
未压缩前,size为924B
用zlib压缩后
const http = require('http')
const fs = require('fs')
const zlib = require('zlib')
const server = http.createServer()
server.on('request', (req, res) => {
console.log('request from', req.url)
const html = fs.readFileSync('index.html')
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Encoding': 'gzip'
})
res.end(zlib.gzipSync(html))
})
server.listen(3003, () => {
console.log('listen http://127.0.0.1:3003')
})
压缩之后,size为602B