来源:Node.js

zlib

Nodejs的zlib模块提供了对数据压缩和解压缩的功能,以便在应用程序中减少数据的传输大小、提高效率

该模块支持多种压缩算法,包括Deflate、Gzip和Raw Deflate,也支持流式操作

gzip和deflate的区别

  • 压缩算法:Gzip内部就使用了Deflate压缩算法,它结合了LZ77算法和哈夫曼编码

    LZ77算法用于数据的重复字符串的替换和引用,而哈夫曼编码用于进一步压缩数据

  • 压缩效率:Gzip压缩通常具有更高的压缩率,因为它使用了哈夫曼编码来进一步压缩数据

    哈夫曼编码根据字符的出现频率,将较常见的字符用较短的编码表示,从而减小数据的大小

  • 压缩速度:Gzip压缩需要更多的计算和处理时间,因为它还要进行哈夫曼编码的步骤,即在压缩速度上,Deflate可能比Gzip更快

  • 应用场景:Gzip压缩常用于文件无损压缩;Deflate适用于网络传输和HTTP响应的内容编码

代码

Gzip

压缩

1
2
3
4
5
6
7
8
9
const zlib = require('node:zlib')
const fs = require('node:fs')

// 创建可读流
const readStream = fs.createReadStream('./README.md')
// 创建可写流
const writeStream = fs.createWriteStream('./README.md.gz') // 压缩完后的后缀是gz
// 使用管道,将可读流数据压缩后再写给可写流
readStream.pipe(zlib.createGzip()).pipe(writeStream)

解压缩

1
2
3
const readStream = fs.createReadStream('./README.md.gz')
const writeStream = fs.createWriteStream('./README.md')
readStream.pipe(zlib.createGunzip()).pipe(writeStream)

Deflate

压缩

1
2
3
const readStream = fs.createReadStream('./README.md')
const writeStream = fs.createWriteStream('./README.md.deflate') // 压缩完后的后缀是deflate
readStream.pipe(zlib.createDeflate()).pipe(writeStream)

解压缩

1
2
3
const readStream = fs.createReadStream('./README.md.deflate')
const writeStream = fs.createWriteStream('./README.md')
readStream.pipe(zlib.createInflate()).pipe(writeStream)

压缩HTTP请求

这是一个返回大量字符的服务

1
2
3
4
5
6
7
8
9
10
11
12
const http = require('node:http')

// 压缩前:458kb
const server = http.createServer((req, res) => {
const txt = 'yjsp'.repeat(114514)
res.setHeader('Content-type', 'text/plain; charset=utf-8')
res.end(txt)
})

server.listen(11451, ()=> {
console.log('server is running on port 11451')
})

将数据压缩后再返回,效果显著

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const zlib = require('node:zlib')
// const fs = require('node:fs')

const http = require('node:http')

const server = http.createServer((req, res) => {
const txt = 'yjsp'.repeat(114514)
res.setHeader('Content-type', 'text/plain; charset=utf-8')

// 需要加上压缩头部

// gzip压缩后:674b
res.setHeader('Content-Encoding', 'gzip')
const result = zlib.gzipSync(txt)

// deflate压缩后:665b
// res.setHeader('Content-Encoding', 'deflate')
// const result = zlib.deflateSync(txt)

res.end(result)
})

server.listen(11451, ()=> {
console.log('server is running on port 11451')
})