Node.js v18.18.0 文档


稳定性: 2 - 稳定

源代码: lib/zlib.js

node:zlib 模块提供了使用 Gzip、Deflate/Inflate、以及 Brotli 实现的压缩功能。

The node:zlib module provides compression functionality implemented using Gzip, Deflate/Inflate, and Brotli.


To access it:

const zlib = require('node:zlib'); 

压缩和解压缩是围绕 Node.js 流 API 构建的。

Compression and decompression are built around the Node.js Streams API.

压缩或解压缩流(例如文件)可以通过将源流通过 zlib Transform 流管道传输到目标流来完成:

Compressing or decompressing a stream (such as a file) can be accomplished by piping the source stream through a zlib Transform stream into a destination stream:

const { createGzip } = require('node:zlib');
const { pipeline } = require('node:stream');
const {
} = require('node:fs');

const gzip = createGzip();
const source = createReadStream('input.txt');
const destination = createWriteStream('input.txt.gz');

pipeline(source, gzip, destination, (err) => {
  if (err) {
    console.error('An error occurred:', err);
    process.exitCode = 1;

// Or, Promisified

const { promisify } = require('node:util');
const pipe = promisify(pipeline);

async function do_gzip(input, output) {
  const gzip = createGzip();
  const source = createReadStream(input);
  const destination = createWriteStream(output);
  await pipe(source, gzip, destination);

do_gzip('input.txt', 'input.txt.gz')
  .catch((err) => {
    console.error('An error occurred:', err);
    process.exitCode = 1;


It is also possible to compress or decompress data in a single step:

const { deflate, unzip } = require('node:zlib');

const input = '.................................';
deflate(input, (err, buffer) => {
  if (err) {
    console.error('An error occurred:', err);
    process.exitCode = 1;

const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
unzip(buffer, (err, buffer) => {
  if (err) {
    console.error('An error occurred:', err);
    process.exitCode = 1;

// Or, Promisified

const { promisify } = require('node:util');
const do_unzip = promisify(unzip);

  .then((buf) => console.log(buf.toString()))
  .catch((err) => {
    console.error('An error occurred:', err);
    process.exitCode = 1;


所有 zlib API,除了那些显式同步的 API,都使用 Node.js 内部线程池。 这可能会在某些应用中导致令人惊讶的效果和性能限制。

All zlib APIs, except those that are explicitly synchronous, use the Node.js internal threadpool. This can lead to surprising effects and performance limitations in some applications.


Creating and using a large number of zlib objects simultaneously can cause significant memory fragmentation.

const zlib = require('node:zlib');

const payload = Buffer.from('This is some data');

for (let i = 0; i < 30000; ++i) {
  zlib.deflate(payload, (err, buffer) => {});

在前面的示例中,同时创建了 30,000 个 deflate 实例。 由于某些操作系统如何处理内存分配和释放,这可能会导致严重的内存碎片。

In the preceding example, 30,000 deflate instances are created concurrently. Because of how some operating systems handle memory allocation and deallocation, this may lead to significant memory fragmentation.


It is strongly recommended that the results of compression operations be cached to avoid duplication of effort.

压缩 HTTP 请求和响应#

node:zlib 模块可用于实现对 HTTP 定义的 gzipdeflatebr 内容编码机制的支持。

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

HTTP Accept-Encoding 标头在 HTTP 请求中用于识别客户端接受的压缩编码。 Content-Encoding 标头用于标识实际应用于消息的压缩编码。

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.

下面给出的示例经过彻底简化以显示基本概念。 使用 zlib 编码可能很昂贵,结果应该被缓存。 有关 zlib 使用中涉及的速度/内存/压缩权衡的更多信息,请参阅 内存使用调整

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('node:zlib');
const http = require('node:http');
const fs = require('node:fs');
const { pipeline } = require('node:stream');

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

  const onError = (err) => {
    if (err) {
      console.error('An error occurred:', err);
      process.exitCode = 1;

  switch (response.headers['content-encoding']) {
    case 'br':
      pipeline(response, zlib.createBrotliDecompress(), output, onError);
    // Or, just use zlib.createUnzip() to handle both of the following cases:
    case 'gzip':
      pipeline(response, zlib.createGunzip(), output, onError);
    case 'deflate':
      pipeline(response, zlib.createInflate(), output, onError);
      pipeline(response, output, onError);
// 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('node:zlib');
const http = require('node:http');
const fs = require('node:fs');
const { pipeline } = require('node:stream');

http.createServer((request, response) => {
  const raw = fs.createReadStream('index.html');
  // Store both a compressed and an uncompressed version of the resource.
  response.setHeader('Vary', 'Accept-Encoding');
  let acceptEncoding = request.headers['accept-encoding'];
  if (!acceptEncoding) {
    acceptEncoding = '';

  const onError = (err) => {
    if (err) {
      // If an error occurs, there's not much we can do because
      // the server has already sent the 200 response code and
      // some amount of data has already been sent to the client.
      // The best we can do is terminate the response immediately
      // and log the error.
      console.error('An error occurred:', err);

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

默认情况下,zlib 方法在解压缩截断数据时会抛出错误。 但是,如果已知数据不完整,或者希望仅检查压缩文件的开头,则可以通过更改用于解压缩输入的最后一个块的刷新方法来抑制默认错误处理数据:

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');

  // For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.
  { finishFlush: zlib.constants.Z_SYNC_FLUSH },
  (err, buffer) => {
    if (err) {
      console.error('An error occurred:', err);
      process.exitCode = 1;

这不会改变其他错误抛出情况下的行为,例如当输入数据的格式无效时。 使用此方法,将无法确定输入是否提前结束或缺少完整性检查,因此需要手动检查解压结果是否有效。

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.


对于基于 zlib 的流#

zlib/zconf.h 开始,针对 Node.js 使用进行了修改:

From zlib/zconf.h, modified for Node.js usage:

deflate 的内存要求是(以字节为单位):

The memory requirements for deflate are (in bytes):

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

那是: windowBits 的 128K = 15 + memLevel 的 128K = 8(默认值)加上小对象的几千字节。

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

例如,要将默认内存要求从 256K 减少到 128K,应将选项设置为:

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.

inflate 的内存要求是(以字节为单位)1 << windowBits。 也就是说,windowBits 的 32K = 15(默认值)加上小对象的几千字节。

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.

这是对大小为 chunkSize 的单个内部输出平板缓冲区的补充,默认为 16K。

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

zlib 压缩的速度受 level 设置的影响最大。 更高的级别将导致更好的压缩,但需要更长的时间才能完成。 较低的级别将导致较少的压缩,但会更快。

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.

一般来说,更大的内存使用选项意味着 Node.js 必须对 zlib 进行更少的调用,因为它能够在每个 write 操作上处理更多的数据。 所以,这是影响速度的另一个因素,以内存使用为代价。

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.

对于基于 Brotli 的流#

有与基于 Brotli 的流的 zlib 选项等效的选项,尽管这些选项的范围与 zlib 的范围不同:

There are equivalents to the zlib options for Brotli-based streams, although these options have different ranges than the zlib ones:

  • zlib 的 level 选项匹配 Brotli 的 BROTLI_PARAM_QUALITY 选项。
  • zlib 的 windowBits 选项匹配 Brotli 的 BROTLI_PARAM_LGWIN 选项。

有关 Brotli 特定选项的更多详细信息,请参阅 below

See below for more details on Brotli-specific options.


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

Calling .flush() on a compression stream will make zlib return as much output as currently possible. This may come at the cost of degraded compression quality, but can be useful when data needs to be available as soon as possible.

在以下示例中,flush() 用于将压缩的部分 HTTP 响应写入客户端:

In the following example, flush() is used to write a compressed partial HTTP response to the client:

const zlib = require('node:zlib');
const http = require('node:http');
const { pipeline } = require('node:stream');

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();
  let i;

  pipeline(output, response, (err) => {
    if (err) {
      // If an error occurs, there's not much we can do because
      // the server has already sent the 200 response code and
      // some amount of data has already been sent to the client.
      // The best we can do is terminate the response immediately
      // and log the error.
      console.error('An error occurred:', err);

  i = 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 常量#

zlib.h 中定义的所有常量也在 require('node:zlib').constants 上定义。 在正常的操作过程中,没有必要使用这些常量。 它们被记录在案,因此它们的存在不足为奇。 本节几乎直接取自 zlib 文档

All of the constants defined in zlib.h are also defined on require('node:zlib').constants. In the normal course of operations, it will not be necessary to use these constants. They are documented so that their presence is not surprising. This section is taken almost directly from the zlib documentation.

以前,常量可直接从 require('node:zlib') 获得,例如 zlib.Z_NO_FLUSH。 目前仍然可以直接从模块访问常量,但已弃用。

Previously, the constants were available directly from require('node:zlib'), for instance zlib.Z_NO_FLUSH. Accessing the constants directly from the module is currently still possible but is deprecated.


Allowed flush values.

  • 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

压缩/解压缩函数的返回代码。 负值是错误,正值用于特殊但正常的事件。

Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events.

  • 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


Compression levels.

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


Compression strategy.

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

Brotli 常量#

有几个选项和其他常量可用于基于 Brotli 的流:

There are several options and other constants available for Brotli-based streams:


以下值是基于 Brotli 的流的有效刷新操作:

The following values are valid flush operations for Brotli-based streams:

  • zlib.constants.BROTLI_OPERATION_PROCESS (所有操作的默认值)
  • zlib.constants.BROTLI_OPERATION_FLUSH(调用 .flush() 时的默认值)
  • zlib.constants.BROTLI_OPERATION_FINISH (最后一个块的默认值)
    • 这个特定的操作可能很难在 Node.js 上下文中使用,因为流层很难知道哪些数据会在这个帧中结束。 此外,目前无法通过 Node.js API 使用这些数据。


可以在 Brotli 编码器上设置几个选项,影响压缩效率和速度。 键和值都可以作为 zlib.constants 对象的属性访问。

There are several options that can be set on Brotli encoders, affecting compression efficiency and speed. Both the keys and the values can be accessed as properties of the zlib.constants object.


The most important options are:

    • BROTLI_MODE_TEXT,针对 UTF-8 文本进行了调整
    • BROTLI_MODE_FONT,针对 WOFF 2.0 字体进行了调整
    • 表示预期输入大小的整数值; 对于未知的输入大小,默认为 0


The following flags can be set for advanced control over the compression algorithm and memory usage tuning:

    • 降低压缩率以提高解压速度的布尔标志。
    • 启用 “大窗口 Brotli” 模式的布尔标志(与 RFC 7932 中标准化的 Brotli 格式不兼容)。
    • 范围从 015 << NPOSTFIX,步长为 1 << NPOSTFIX



These advanced options are available for controlling decompression:

    • 影响内部内存分配模式的布尔标志。
    • 启用 “大窗口 Brotli” 模式的布尔标志(与 RFC 7932 中标准化的 Brotli 格式不兼容)。


每个基于 zlib 的类都有一个 options 对象。 不需要任何选项。

Each zlib-based class takes an options object. No options are required.


Some options are only relevant when compressing and are ignored by the decompression classes.

有关更多信息,请参阅 deflateInit2inflateInit2 文档。

See the deflateInit2 and inflateInit2 documentation for more information.


每个基于 Brotli 的类都有一个 options 对象。 所有选项都是可选的。

Each Brotli-based class takes an options object. All options are optional.


For example:

const stream = zlib.createBrotliCompress({
  chunkSize: 32 * 1024,
  params: {
    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,
    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size,


使用 Brotli 算法压缩数据。

Compress data using the Brotli algorithm.


使用 Brotli 算法解压缩数据。

Decompress data using the Brotli algorithm.


使用 deflate 压缩数据。

Compress data using deflate.


使用 deflate 压缩数据,并且不附加 zlib 标头。

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


解压缩 gzip 流。

Decompress a gzip stream.


使用 gzip 压缩数据。

Compress data using gzip.


解压缩 deflate 流。

Decompress a deflate stream.


解压缩原始的 deflate 流。

Decompress a raw deflate stream.


通过自动检测标头来解压缩 Gzip 或 Deflate 压缩的流。

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


不是由 node:zlib 模块导出的。 它记录在此处,因为它是压缩器/解压缩器类的基类。

Not exported by the node:zlib module. It is documented here because it is the base class of the compressor/decompressor classes.

这个类继承自 stream.Transform,允许在管道和类似的流操作中使用 node:zlib 对象。

This class inherits from stream.Transform, allowing node:zlib objects to be used in pipes and similar stream operations.


稳定性: 0 - 弃用: 改用 zlib.bytesWritten

弃用的 zlib.bytesWritten 别名。 选择这个原始名称是因为将值解释为引擎读取的字节数也是有意义的,但与 Node.js 中以这些名称公开值的其他流不一致。

Deprecated alias for zlib.bytesWritten. This original name was chosen because it also made sense to interpret the value as the number of bytes read by the engine, but is inconsistent with other streams in Node.js that expose values under these names.


zlib.bytesWritten 属性指定在处理字节(压缩或解压缩,视派生类而定)之前写入引擎的字节数。

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



Close the underlying handle.

zlib.flush([kind, ]callback)#

  • kind 默认值: zlib.constants.Z_FULL_FLUSH 用于基于 zlib 的流,zlib.constants.BROTLI_OPERATION_FLUSH 用于基于 Brotli 的流。
  • callback <Function>

刷新挂起的数据。 不要轻率地称之为,过早刷新会对压缩算法的有效性产生负面影响。

Flush pending data. Don't call this frivolously, premature flushes negatively impact the effectiveness of the compression algorithm.

调用它只会从内部 zlib 状态刷新数据,并且不会在流级别执行任何类型的刷新。 相反,它的行为类似于对 .write() 的正常调用,即它将排队等待其他未决写入,并且仅在从流中读取数据时才产生输出。

Calling this only flushes data from the internal zlib state, and does not perform flushing of any kind on the streams level. Rather, it behaves like a normal call to .write(), i.e. it will be queued up behind other pending writes and will only produce output when data is being read from the stream.

zlib.params(level, strategy, callback)#

此函数仅适用于基于 zlib 的流,即不适用于 Brotli。

This function is only available for zlib-based streams, i.e. not Brotli.

动态更新压缩级别和压缩策略。 仅适用于 deflate 算法。

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


将压缩器/解压缩器重置为出厂默认设置。 仅适用于 inflate 和 deflate 算法。

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


提供枚举 Zlib 相关常量的对象。

Provides an object enumerating Zlib-related constants.


创建并返回新的 BrotliCompress 对象。

Creates and returns a new BrotliCompress object.


创建并返回新的 BrotliDecompress 对象。

Creates and returns a new BrotliDecompress object.


创建并返回新的 Deflate 对象。

Creates and returns a new Deflate object.


创建并返回新的 DeflateRaw 对象。

Creates and returns a new DeflateRaw object.

当原始 deflate 流的 windowBits 设置为 8 时,zlib 从 1.2.8 到 1.2.11 的升级改变了行为。 如果最初设置为 8,则 zlib 会自动将 windowBits 设置为 9。 较新版本的 zlib 会抛出异常,因此 Node.js 恢复了将值从 8 升级到 9 的原始行为,因为将 windowBits = 9 传给 zlib 实际上会产生一个仅有效使用 8 位窗口的压缩流。

An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when windowBits is set to 8 for raw deflate streams. zlib would automatically set windowBits to 9 if was initially set to 8. Newer versions of zlib will throw an exception, so Node.js restored the original behavior of upgrading a value of 8 to 9, since passing windowBits = 9 to zlib actually results in a compressed stream that effectively uses an 8-bit window only.


创建并返回新的 Gunzip 对象。

Creates and returns a new Gunzip object.


创建并返回新的 Gzip 对象。 参见 示例

Creates and returns a new Gzip object. See example.


创建并返回新的 Inflate 对象。

Creates and returns a new Inflate object.


创建并返回新的 InflateRaw 对象。

Creates and returns a new InflateRaw object.


创建并返回新的 Unzip 对象。

Creates and returns a new Unzip object.


所有这些都将 BufferTypedArrayDataViewArrayBuffer 或字符串作为第一个参数,可选的第二个参数为 zlib 类提供选项,并将使用 callback(error, result) 调用提供的回调。

All of these take a Buffer, TypedArray, DataView, ArrayBuffer or string as the first argument, an optional second argument to supply options to the zlib classes and will call the supplied callback with callback(error, result).

每个方法都有一个对应的 *Sync 方法,它们接受相同的参数,但没有回调。

Every method has a *Sync counterpart, which accept the same arguments, but without a callback.

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

zlib.brotliCompressSync(buffer[, options])#

使用 BrotliCompress 压缩数据块。

Compress a chunk of data with BrotliCompress.

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

zlib.brotliDecompressSync(buffer[, options])#

使用 BrotliDecompress 解压缩数据块。

Decompress a chunk of data with BrotliDecompress.

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

zlib.deflateSync(buffer[, options])#

使用 Deflate 压缩数据块。

Compress a chunk of data with Deflate.

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

zlib.deflateRawSync(buffer[, options])#

使用 DeflateRaw 压缩数据块。

Compress a chunk of data with DeflateRaw.

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

zlib.gunzipSync(buffer[, options])#

使用 Gunzip 解压缩数据块。

Decompress a chunk of data with Gunzip.

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

zlib.gzipSync(buffer[, options])#

使用 Gzip 压缩数据块。

Compress a chunk of data with Gzip.

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

zlib.inflateSync(buffer[, options])#

使用 Inflate 解压缩数据块。

Decompress a chunk of data with Inflate.

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

zlib.inflateRawSync(buffer[, options])#

使用 InflateRaw 解压缩数据块。

Decompress a chunk of data with InflateRaw.

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

zlib.unzipSync(buffer[, options])#

使用 Unzip 解压缩数据块。

Decompress a chunk of data with Unzip.