Skip to content

Node.js zlib 模块

zlib 提供数据压缩和解压缩功能,减少传输大小、提高性能,支持 Gzip / Deflate 等多种格式。

文件压缩/解压(流式)

Gzip 格式

js
const zlib = require('zlib')
const fs = require('node:fs')

// 压缩:439KB → 4B(纯文本压缩率极高)
fs.createReadStream('index.txt')
  .pipe(zlib.createGzip())
  .pipe(fs.createWriteStream('index.txt.gz'))

// 解压
fs.createReadStream('index.txt.gz')
  .pipe(zlib.createGunzip())
  .pipe(fs.createWriteStream('index2.txt'))

Deflate 格式

js
// 压缩
fs.createReadStream('index.txt')
  .pipe(zlib.createDeflate())
  .pipe(fs.createWriteStream('index.txt.deflate'))

// 解压
fs.createReadStream('index.txt.deflate')
  .pipe(zlib.createInflate())
  .pipe(fs.createWriteStream('index3.txt'))

Gzip vs Deflate

GzipDeflate
算法Deflate + 哈夫曼编码LZ77 + 哈夫曼
压缩率更高稍低
速度稍慢(多一步哈夫曼编码)更快
场景Web 服务器、HTTP 内容编码通用压缩

HTTP 响应压缩

实际应用中,在 HTTP 服务器开启 Gzip/Deflate 可大幅减少传输数据量:

js
const server = http.createServer((req, res) => {
  const txt = '小满zs'.repeat(1000)

  // 方式一:Gzip(8.2KB → 245B)
  res.setHeader('Content-Encoding', 'gzip')
  res.end(zlib.gzipSync(txt))

  // 方式二:Deflate(8.2KB → 236B)
  // res.setHeader('Content-Encoding', 'deflate')
  // res.end(zlib.deflateSync(txt))
})
server.listen(3000)

Content-Encoding 响应头告诉浏览器以对应格式解压。开发中通常由中间件(如 compression)自动处理。