zlib
要学习压缩,首先要了解两个头, Content-Encoding: gzip 服务端 ,Accept-Encoding: gzip, deflate, br 客户端, 我们根据客户端支持的压缩模式,进行压缩文件,然后返回给客户端,并设置响应头,告诉客户端用那种方式解压文件, 下边是zlib的使用方式
let fs = require('fs')
let path = require('path')
let zlib = require('zlib')
function zip (src) {
let pathInfo = path.parse(src)
let gzip = zlib.createGzip()
fs.createReadStream(src)
.pipe(gzip)
.pipe(fs.createWriteStream(`${pathInfo.dir}/${pathInfo.name}.gz`))
}
function unzip (src) {
let pathInfo = path.parse(src)
let gunzip = zlib.createGunzip()
fs.createReadStream(src)
.pipe(gunzip)
.pipe(fs.createWriteStream(`${pathInfo.dir}/${pathInfo.name}${pathInfo.name}.txt`))
}
unzip(path.join(__dirname, './1.gz'))
这里是一个简单的服务端的用例
let fs = require('fs')
let path = require('path')
let zlib = require('zlib')
let http = require('http')
let server = http.createServer(function(req, res) {
let p = path.join(__dirname, './1.txt')
let header = req.headers['accept-encoding']
res.setHeader('Content-Type', 'text/html;charset=utf8')
if (header) {
if (header.match(/\bgzip\b/)) {
let gzip = zlib.createGzip()
res.setHeader('Content-Encoding', 'gzip')
fs.createReadStream(p)
.pipe(gzip)
.pipe(res)
} else if(header.match(/\bdeflate\b/)) {
let deflate = zlib.createDeflate()
res.setHeader('Content-Encoding', 'deflate')
fs.createReadStream(p)
.pipe(deflate)
.pipe(res)
} else {
fs.createReadStream(p)
.pipe(res)
}
} else {
fs.createReadStream(p)
.pipe(res)
}
})
server.listen(5000)
server.on('listening', () => {
console.log('http启动完成')
})
server.on('close', () => {
console.log('服务器关闭')
})
总结
以上就是简单的服务端压缩,然后设置响应头,高速浏览器怎么解析,上边展示了使用gzip和deflate两种模式,没有特别高深的东西,就是简单的api调用