Node.js v8.1.2 文档


查看英文版 / 参与翻译

Stability: 2 - Stable

zlib模块提供通过 Gzip 和 Deflate/Inflate 实现的压缩功能,可以通过这样使用它

const zlib = require('zlib');


const gzip = zlib.createGzip();
const fs = require('fs');
const inp = fs.createReadStream('input.txt');
const out = fs.createWriteStream('input.txt.gz');



const input = '.................................';
zlib.deflate(input, (err, buffer) => {
  if (!err) {
  } else {
    // handle error

const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
zlib.unzip(buffer, (err, buffer) => {
  if (!err) {
  } else {
    // handle error

Compressing HTTP requests and responses#

查看英文版 / 参与翻译

The zlib module can be used to implement support for the gzip and deflate content-encoding mechanisms defined by HTTP.

The HTTP Accept-Encoding header is used within an http request to identify the compression encodings accepted by the client. The Content-Encoding header is used to identify the compression encodings actually applied to a message.

Note: the examples given below are drastically simplified to show the basic concept. Using zlib encoding can be expensive, and the results ought to be cached. See Memory Usage Tuning for more information on the speed/memory/compression tradeoffs involved in zlib usage.

// client request example
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
const request = http.get({ host: '',
                           path: '/',
                           port: 80,
                           headers: { 'Accept-Encoding': 'gzip,deflate' } });
request.on('response', (response) => {
  const output = fs.createWriteStream('example.com_index.html');

  switch (response.headers['content-encoding']) {
    // or, just use zlib.createUnzip() to handle both cases
    case 'gzip':
    case 'deflate':
// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
http.createServer((request, response) => {
  const raw = fs.createReadStream('index.html');
  let acceptEncoding = request.headers['accept-encoding'];
  if (!acceptEncoding) {
    acceptEncoding = '';

  // Note: This is not a conformant accept-encoding parser.
  // See
  if (/\bdeflate\b/.test(acceptEncoding)) {
    response.writeHead(200, { 'Content-Encoding': 'deflate' });
  } else if (/\bgzip\b/.test(acceptEncoding)) {
    response.writeHead(200, { 'Content-Encoding': 'gzip' });
  } else {
    response.writeHead(200, {});

By default, the zlib methods will throw an error when decompressing truncated data. However, if it is known that the data is incomplete, or the desire is to inspect only the beginning of a compressed file, it is possible to suppress the default error handling by changing the flushing method that is used to decompress the last chunk of input data:

// This is a truncated version of the buffer from the above examples
const buffer = Buffer.from('eJzT0yMA', 'base64');

  { finishFlush: zlib.constants.Z_SYNC_FLUSH },
  (err, buffer) => {
    if (!err) {
    } else {
      // handle error

This will not change the behavior in other error-throwing situations, e.g. when the input data has an invalid format. Using this method, it will not be possible to determine whether the input ended prematurely or lacks the integrity checks, making it necessary to manually check that the decompressed result is valid.

Memory Usage Tuning#

查看英文版 / 参与翻译

From zlib/zconf.h, modified to node.js's usage:

The memory requirements for deflate are (in bytes):

(1 << (windowBits + 2)) + (1 << (memLevel + 9))

That is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects.

For example, to reduce the default memory requirements from 256K to 128K, the options should be set to:

const options = { windowBits: 14, memLevel: 7 };

This will, however, generally degrade compression.

The memory requirements for inflate are (in bytes) 1 << windowBits. That is, 32K for windowBits=15 (default value) plus a few kilobytes for small objects.

This is in addition to a single internal output slab buffer of size chunkSize, which defaults to 16K.

The speed of zlib compression is affected most dramatically by the level setting. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster.

In general, greater memory usage options will mean that Node.js has to make fewer calls to zlib because it will be able to process more data on each write operation. So, this is another factor that affects the speed, at the cost of memory usage.


查看英文版 / 参与翻译

在压缩流上调用 .flush() 方法将使 zlib 返回尽可能多的输出. 这可能是以压缩质量下降 为代价的,但是当需要尽快提供数据时,这可能是有用的

在以下的实例中, flush() 方法用于将部分压缩过的 HTTP 响应返回给客户端:

const zlib = require('zlib');
const http = require('http');

http.createServer((request, response) => {
  // For the sake of simplicity, the Accept-Encoding checks are omitted.
  response.writeHead(200, { 'content-encoding': 'gzip' });
  const output = zlib.createGzip();

  setInterval(() => {
    output.write(`The current time is ${Date()}\n`, () => {
      // The data has been passed to zlib, but the compression algorithm may
      // have decided to buffer the data for more efficient compression.
      // Calling .flush() will make the data available as soon as the client
      // is ready to receive it.
  }, 1000);


查看英文版 / 参与翻译

这些被定义在 zlib.h 的全部常量同时也被定义在 require('zlib').constants 常量上. 不需要在正常的操作中使用这些常量. 记录他们为了使他们的存在并不奇怪. 这个章节几乎直接取自zlib documentation. 参阅 获取更多信息.

注意: 以前, 可以直接从 require('zlib') 中获取到这些常量, 例如 zlib.Z_NO_FLUSH. 目前仍然可以从模块中直接访问这些常量, 但是不推荐使用.

可接受的 flush 值.

  • zlib.constants.Z_NO_FLUSH
  • zlib.constants.Z_PARTIAL_FLUSH
  • zlib.constants.Z_SYNC_FLUSH
  • zlib.constants.Z_FULL_FLUSH
  • zlib.constants.Z_FINISH
  • zlib.constants.Z_BLOCK
  • zlib.constants.Z_TREES

返回压缩/解压函数的返回值. 发送错误时为负值, 正值用于特殊但正常的事件.

  • zlib.constants.Z_OK
  • zlib.constants.Z_STREAM_END
  • zlib.constants.Z_NEED_DICT
  • zlib.constants.Z_ERRNO
  • zlib.constants.Z_STREAM_ERROR
  • zlib.constants.Z_DATA_ERROR
  • zlib.constants.Z_MEM_ERROR
  • zlib.constants.Z_BUF_ERROR
  • zlib.constants.Z_VERSION_ERROR


  • zlib.constants.Z_NO_COMPRESSION
  • zlib.constants.Z_BEST_SPEED
  • zlib.constants.Z_BEST_COMPRESSION
  • zlib.constants.Z_DEFAULT_COMPRESSION


  • zlib.constants.Z_FILTERED
  • zlib.constants.Z_HUFFMAN_ONLY
  • zlib.constants.Z_RLE
  • zlib.constants.Z_FIXED
  • zlib.constants.Z_DEFAULT_STRATEGY

Class Options#

查看英文版 / 参与翻译

每一个类都有一个 options 对象. 所有的选项都是可选的.

注意一些选项只与压缩相关, 会被解压类忽视.

更多信息查阅在 关于 deflateInit2 以及 inflateInit2 的描述,

Class: zlib.Deflate#

查看英文版 / 参与翻译

Compress data using deflate.

Class: zlib.DeflateRaw#

查看英文版 / 参与翻译

Compress data using deflate, and do not append a zlib header.

Class: zlib.Gunzip#

查看英文版 / 参与翻译

Decompress a gzip stream.

Class: zlib.Gzip#

查看英文版 / 参与翻译

Compress data using gzip.

Class: zlib.Inflate#

查看英文版 / 参与翻译

Decompress a deflate stream.

Class: zlib.InflateRaw#

查看英文版 / 参与翻译

Decompress a raw deflate stream.

Class: zlib.Unzip#

查看英文版 / 参与翻译

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header.

Class: zlib.Zlib#

查看英文版 / 参与翻译

没有被 zlib 模块导出. 它被记录于此因为它是 compressor/decompressor 类的基础类.


查看英文版 / 参与翻译

The zlib.bytesRead property specifies the number of bytes read by the engine before the bytes are processed (compressed or decompressed, as appropriate for the derived class).

zlib.flush([kind], callback)#

查看英文版 / 参与翻译

kind 默认为 zlib.constants.Z_FULL_FLUSH.

刷新挂起的数据. 不要轻易的调用这个方法, 过早的刷新会对压缩算法造成负面影响.

执行这个操作只会从 zlib 内部状态刷新数据, 不会在流级别上执行任何类型的刷新. 相反, 它的表现 类似正常的 .write() 调用. 即它将在队列中其他数据写入操作之后执行,并且只会在从流中读取数据之后 才产生输出。

zlib.params(level, strategy, callback)#

查看英文版 / 参与翻译

Dynamically update the compression level and compression strategy. Only applicable to deflate algorithm.


查看英文版 / 参与翻译

Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms.


查看英文版 / 参与翻译

Provides an object enumerating Zlib-related constants.


查看英文版 / 参与翻译

Returns a new Deflate object with an options.


查看英文版 / 参与翻译

返回一个带有 options 的 新的 DeflateRaw 对象.

注意: zlib 库拒绝 256-字节的 windows 的请求 (即 {windowBits: 8} in options). 当创建具有这个特定 windowBits 值的 DeflateRaw 对象时, 会抛出一个 Error


查看英文版 / 参与翻译

Returns a new Gunzip object with an options.


查看英文版 / 参与翻译

Returns a new Gzip object with an options.


查看英文版 / 参与翻译

Returns a new Inflate object with an options.


查看英文版 / 参与翻译

Returns a new InflateRaw object with an options.


查看英文版 / 参与翻译

Returns a new Unzip object with an options.

Convenience Methods#

查看英文版 / 参与翻译

所有这些方法都将 [Buffer][], [TypeArray][], [DataView][], 或者字符串作为第一个 参数, 一个回调函数作为可选的第二个参数提供给 zlib 类, 会在 callback(error, result) 中调用.

每一个方法相对应的都有一个接受相同参数, 但是没有回调的 *Sync 版本.

zlib.deflate(buffer[, options], callback)#

查看英文版 / 参与翻译

zlib.deflateSync(buffer[, options])#

查看英文版 / 参与翻译

Compress a Buffer or string with Deflate.

zlib.deflateRaw(buffer[, options], callback)#

查看英文版 / 参与翻译

zlib.deflateRawSync(buffer[, options])#

查看英文版 / 参与翻译

Compress a Buffer or string with DeflateRaw.

zlib.gunzip(buffer[, options], callback)#

查看英文版 / 参与翻译

zlib.gunzipSync(buffer[, options])#

查看英文版 / 参与翻译

Decompress a Buffer or string with Gunzip.

zlib.gzip(buffer[, options], callback)#

查看英文版 / 参与翻译

zlib.gzipSync(buffer[, options])#

查看英文版 / 参与翻译

Compress a Buffer or string with Gzip.

zlib.inflate(buffer[, options], callback)#

查看英文版 / 参与翻译

zlib.inflateSync(buffer[, options])#

查看英文版 / 参与翻译

Decompress a Buffer or string with Inflate.

zlib.inflateRaw(buffer[, options], callback)#

查看英文版 / 参与翻译

zlib.inflateRawSync(buffer[, options])#

查看英文版 / 参与翻译

Decompress a Buffer or string with InflateRaw.

zlib.unzip(buffer[, options], callback)#

查看英文版 / 参与翻译

zlib.unzipSync(buffer[, options])#

查看英文版 / 参与翻译

Decompress a Buffer or string with Unzip.