gzip 和 deflate 的基本使用
js
const zlib = require("zlib");
const fs = require('fs')
// 压缩 1. createGzip .gz 2. createDeflate .deflate
// const readStream = fs.createReadStream('index.txt')
// const writeStream = fs.createWriteStream('index.txt.gz')
// readStream.pipe(zlib.createGzip()).pipe(writeStream)
//解压 1. createGunzip 2. createInflate
// const readStream = fs.createReadStream('index.txt.gz')
// const writeStream = fs.createWriteStream('index2.txt')
// readStream.pipe(zlib.createGunzip()).pipe(writeStream)
const readStream = fs.createReadStream('index.txt')
const writeStream = fs.createWriteStream('index.txt.deflate')
readStream.pipe(zlib.createDeflate()).pipe(writeStream)
gzip 和 deflate 的区别
-
压缩算法:Gzip 使用 LZ77 算法和哈夫曼编码。所以 gzip 慢于 deflate 且压缩后文件大于 deflate。
-
应用场景:Gzip 压缩常用于文件压缩,deflate 适用于网络传输和 HTTP 响应的内容编码。
js
const zlib = require("zlib");
const http = require('http')
// 直接写入 17.2 kB / gzip 289 B / deflate 279 B
const server = http.createServer((req,res)=> {
const txt = '我是糕手 O.o '.repeat(1000)
res.setHeader('Content-Encoding', 'deflate')
res.setHeader('Content-Type', 'text/plan;charset=utf-8')
let result = zlib.deflateSync(txt)
res.end(result)
})
server.listen(3000,()=> {
console.log('服务器3000端口已启动...')
})