目录

zlib(压缩)#

稳定性: 2 - 稳定

源代码: lib/zlib.js

zlib 模块提供通过 Gzip、Deflate/Inflate、和 Brotli 实现的压缩功能。

可以通过这样使用它:

const zlib = require('zlib');

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

压缩或者解压流(例如一个文件)通过 zlib Transform 流将源数据流传输到目标流中来完成。

const { createGzip } = require('zlib');
const { pipeline } = require('stream');
const {
  createReadStream,
  createWriteStream
} = require('fs');

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

pipeline(source, gzip, destination, (err) => {
  if (err) {
    console.error('发生错误:', err);
    process.exitCode = 1;
  }
});

// 或 Promise 化:

const { promisify } = require('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('发生错误:', err);
    process.exitCode = 1;
  });

数据的压缩或解压缩也可以只用一个步骤完成:

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

const input = '.................................';
deflate(input, (err, buffer) => {
  if (err) {
    console.error('发生错误:', err);
    process.exitCode = 1;
  }
  console.log(buffer.toString('base64'));
});

const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
unzip(buffer, (err, buffer) => {
  if (err) {
    console.error('发生错误:', err);
    process.exitCode = 1;
  }
  console.log(buffer.toString());
});

// 或 Promise 化:

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

do_unzip(buffer)
  .then((buf) => console.log(buf.toString()))
  .catch((err) => {
    console.error('发生错误:', err);
    process.exitCode = 1;
  });

线程池的用法与性能的注意事项#

除显式同步的 API 之外,所有 zlib API 均使用 Node.js 内部的线程池。 这可能会在某些应用程序中产生意外的效果或性能限制。

同时创建和使用大量的 zlib 对象可能会导致明显的内存碎片。

const zlib = require('zlib');

const payload = Buffer.from('这是一些数据');

// 警告:请勿这样做!
for (let i = 0; i < 30000; ++i) {
  zlib.deflate(payload, (err, buffer) => {});
}

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

强烈建议对压缩操作的结果进行缓存,以避免重复工作。

压缩 HTTP 的请求和响应#

zlib 模块可以用来实现对 HTTP 中定义的 gzipdeflate 内容编码机制的支持。

HTTP 的 Accept-Encoding 消息头用来标记客户端接受的压缩编码。 Content-Encoding 消息头用于标识实际应用于消息的压缩编码。

下面给出的示例大幅简化,用以展示了基本的概念。 使用 zlib 编码成本会很高, 结果应该被缓存。 关于 zlib 使用中有关速度/内存/压缩互相权衡的信息,查阅内存使用的调整

// 客户端请求示例。
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
const { pipeline } = require('stream');

const request = http.get({ host: 'example.com',
                           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('发生错误:', err);
      process.exitCode = 1;
    }
  };

  switch (response.headers['content-encoding']) {
    case 'br':
      pipeline(response, zlib.createBrotliDecompress(), output, onError);
      break;
    // 或者, 只是使用 zlib.createUnzip() 方法去处理这两种情况:
    case 'gzip':
      pipeline(response, zlib.createGunzip(), output, onError);
      break;
    case 'deflate':
      pipeline(response, zlib.createInflate(), output, onError);
      break;
    default:
      pipeline(response, output, onError);
      break;
  }
});
// 服务端示例。
// 对每一个请求运行 gzip 操作的成本是十分高昂的。
// 缓存已压缩的 buffer 是更加高效的方式。
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
const { pipeline } = require('stream');

http.createServer((request, response) => {
  const raw = fs.createReadStream('index.html');
  // 存储资源的压缩版本和未压缩版本。
  response.setHeader('Vary', 'Accept-Encoding');
  let acceptEncoding = request.headers['accept-encoding'];
  if (!acceptEncoding) {
    acceptEncoding = '';
  }

  const onError = (err) => {
    if (err) {
      // 如果发生错误,则我们将会无能为力,
      // 因为服务器已经发送了 200 响应码,
      // 并且已经向客户端发送了一些数据。 
      // 我们能做的最好就是立即终止响应并记录错误。
      response.end();
      console.error('发生错误:', err);
    }
  };

  // 注意:这不是一个合适的 accept-encoding 解析器。
  // 查阅 https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
  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);
  }
}).listen(1337);

默认情况下,当解压不完整的数据时 zlib 方法会抛出一个错误。 然而,如果它已经知道数据是不完整的,或者仅仅是为了检查已压缩文件的开头,可以通过改变用来解压最后一个的输入数据块的刷新方法来避免默认的错误处理:

// 这是一个上面例子中 buffer 的不完整版本。
const buffer = Buffer.from('eJzT0yMA', 'base64');

zlib.unzip(
  buffer,
  // 对于 Brotli,等效的是 zlib.constants.BROTLI_OPERATION_FLUSH。
  { finishFlush: zlib.constants.Z_SYNC_FLUSH },
  (err, buffer) => {
    if (err) {
      console.error('发生错误:', err);
      process.exitCode = 1;
    }
    console.log(buffer.toString());
  });

这不会改变其他抛出错误情况下的行为,例如,当输入内容的格式无效时。 使用这个方法,无法确定输入是否过早结束,或者缺乏完整性检查,因此有必要人工检查解压结果是否有效。

内存使用的调整#

对于基于 zlib 的流#

来自 zlib/zconf.h,修改为 node.js 的用法:

解压所需的内存是(字节为单位):

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

就是: 当设置为 windowBits = 15 和 memLevel = 8 时(默认值),小的对象需要 128K 加上几千字节。

例如,为了将默认内存需求 256K 减少到 128K,应该这样设置:

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

这能实现,然而,通常会降低压缩水平。

压缩所需的内存是 1 << windowBits(字节为单位)。 既是, 设置为 windowBits = 15(默认值)时,小的对象需要 32K 加上几千字节。

这是一个大小为 chunkSize 单个内部输出 slab 缓冲,默认为 16K。

level 的设置是影响 zlib 压缩速度最大因素。 更高的等级设置会得到更高的压缩水平,然而需要更长的时间完成。 较低的等级设置会导致较少的压缩,但会大大加快速度。

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

对于基于 Brotli 的流#

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

  • zlib’s level option matches Brotli’s BROTLI_PARAM_QUALITY option.
  • zlib’s windowBits option matches Brotli’s BROTLI_PARAM_LGWIN option.

See below for more details on Brotli-specific options.

刷新#

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

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

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

http.createServer((request, response) => {
  // 为了简单起见,省略了对 Accept-Encoding 的检测。
  response.writeHead(200, { 'content-encoding': 'gzip' });
  const output = zlib.createGzip();
  let i;

  pipeline(output, response, (err) => {
    if (err) {
      // 如果发生错误,则我们将会无能为力,
      // 因为服务器已经发送了 200 响应码,
      // 并且已经向客户端发送了一些数据。 
      // 我们能做的最好就是立即终止响应并记录错误。
      clearInterval(i);
      response.end();
      console.error('发生错误:', err);
    }
  });

  i = setInterval(() => {
    output.write(`The current time is ${Date()}\n`, () => {
      // 数据已经传递给了 zlib,但压缩算法看能已经决定缓存数据以便得到更高的压缩效率。
      // 一旦客户端准备接收数据,调用 .flush() 将会使数据可用。
      output.flush();
    });
  }, 1000);
}).listen(1337);

常量#

zlib 常量#

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

以前,可以直接从 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

Brotli 常量#

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

刷新操作#

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

  • zlib.constants.BROTLI_OPERATION_PROCESS (default for all operations)
  • zlib.constants.BROTLI_OPERATION_FLUSH (default when calling .flush())
  • zlib.constants.BROTLI_OPERATION_FINISH (default for the last chunk)
  • zlib.constants.BROTLI_OPERATION_EMIT_METADATA
    • This particular operation may be hard to use in a Node.js context, as the streaming layer makes it hard to know which data will end up in this frame. Also, there is currently no way to consume this data through the Node.js API.

压缩器选项#

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_PARAM_MODE
    • BROTLI_MODE_GENERIC (default)
    • BROTLI_MODE_TEXT, adjusted for UTF-8 text
    • BROTLI_MODE_FONT, adjusted for WOFF 2.0 fonts
  • BROTLI_PARAM_QUALITY
    • Ranges from BROTLI_MIN_QUALITY to BROTLI_MAX_QUALITY, with a default of BROTLI_DEFAULT_QUALITY.
  • BROTLI_PARAM_SIZE_HINT
    • Integer value representing the expected input size; defaults to 0 for an unknown input size.

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

  • BROTLI_PARAM_LGWIN
    • Ranges from BROTLI_MIN_WINDOW_BITS to BROTLI_MAX_WINDOW_BITS, with a default of BROTLI_DEFAULT_WINDOW, or up to BROTLI_LARGE_MAX_WINDOW_BITS if the BROTLI_PARAM_LARGE_WINDOW flag is set.
  • BROTLI_PARAM_LGBLOCK
    • Ranges from BROTLI_MIN_INPUT_BLOCK_BITS to BROTLI_MAX_INPUT_BLOCK_BITS.
  • BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING
    • Boolean flag that decreases compression ratio in favour of decompression speed.
  • BROTLI_PARAM_LARGE_WINDOW
    • Boolean flag enabling “Large Window Brotli” mode (not compatible with the Brotli format as standardized in RFC 7932).
  • BROTLI_PARAM_NPOSTFIX
    • Ranges from 0 to BROTLI_MAX_NPOSTFIX.
  • BROTLI_PARAM_NDIRECT
    • Ranges from 0 to 15 << NPOSTFIX in steps of 1 << NPOSTFIX.

解压器选项#

These advanced options are available for controlling decompression:

  • BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION
    • Boolean flag that affects internal memory allocation patterns.
  • BROTLI_DECODER_PARAM_LARGE_WINDOW
    • Boolean flag enabling “Large Window Brotli” mode (not compatible with the Brotli format as standardized in RFC 7932).

Options 类#

每一个类都有一个 options 对象。 所有的选项都不是必需的。

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

更多信息请查阅 deflateInit2inflateInit2 文档。

BrotliOptions 类#

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

zlib.BrotliCompress 类#

Compress data using the Brotli algorithm.

zlib.BrotliDecompress 类#

Decompress data using the Brotli algorithm.

zlib.Deflate 类#

使用 deflate 压缩数据。

zlib.DeflateRaw 类#

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

zlib.Gunzip 类#

解压缩 gzip 流。

zlib.Gzip 类#

使用 gzip 压缩数据。

zlib.Inflate 类#

解压一个 deflate 流。

zlib.InflateRaw 类#

解压一个原始的 deflate 流。

zlib.Unzip 类#

通过自动检测头信息解压 Gzip 或者 Deflate 压缩的流.

zlib.ZlibBase 类#

未被 zlib 模块导出。 在此进行记录,因为它是压缩器/解压缩器类的基类。

该类继承自 stream.Transform,允许 zlib 对象用于管道和类似的流操作中。

zlib.bytesRead#

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

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#

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

zlib.close([callback])#

Close the underlying handle.

zlib.flush([kind, ]callback)#

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

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

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

zlib.params(level, strategy, callback)#

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

动态更新压缩等级和压缩策略。 只对解压算法有效。

zlib.reset()#

重置 compressor/decompressor 为默认值。仅适用于 inflate 和 deflate 算法。

zlib.constants#

Provides an object enumerating Zlib-related constants.

zlib.createBrotliCompress([options])#

Creates and returns a new BrotliCompress object.

zlib.createBrotliDecompress([options])#

Creates and returns a new BrotliDecompress object.

zlib.createDeflate([options])#

创建并返回一个新的 Deflate 对象。

zlib.createDeflateRaw([options])#

Creates and returns a new DeflateRaw object.

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.

zlib.createGunzip([options])#

创建并返回一个新的 Gunzip 对象。

zlib.createGzip([options])#

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

zlib.createInflate([options])#

创建并返回一个新的 Inflate 对象。

zlib.createInflateRaw([options])#

创建并返回一个新的 InflateRaw 对象。

zlib.createUnzip([options])#

创建并返回一个新的 Unzip 对象。

便利的方法#

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

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

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

zlib.brotliCompressSync(buffer[, options])#

Compress a chunk of data with BrotliCompress.

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

zlib.brotliDecompressSync(buffer[, options])#

Decompress a chunk of data with BrotliDecompress.

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

zlib.deflateSync(buffer[, options])#

使用 Deflate 压缩一个数据块。

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

zlib.deflateRawSync(buffer[, options])#

使用 DeflateRaw 压缩一个数据块。

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

zlib.gunzipSync(buffer[, options])#

使用 Gunzip 解压缩一个数据块。

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

zlib.gzipSync(buffer[, options])#

使用 Gzip 压缩一个数据块。

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

zlib.inflateSync(buffer[, options])#

使用 Inflate 解压缩一个数据块。

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

zlib.inflateRawSync(buffer[, options])#

使用 InflateRaw 解压缩一个数据块。

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

zlib.unzipSync(buffer[, options])#

使用 Unzip 解压缩一个数据块。