Node.js v12.4.0 文档


目录

Zlib#

中英对照提交修改

稳定性: 2 - 稳定

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

const zlib = require('zlib');

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

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

inp.pipe(gzip).pipe(out);

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

const input = '.................................';
zlib.deflate(input, (err, buffer) => {
  if (!err) {
    console.log(buffer.toString('base64'));
  } else {
    // 错误处理
  }
});

const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
zlib.unzip(buffer, (err, buffer) => {
  if (!err) {
    console.log(buffer.toString());
  } else {
    // 错误处理
  }
});

Threadpool Usage#

暂无中英对照提交修改

Note that all zlib APIs except those that are explicitly synchronous use libuv's threadpool. This can lead to surprising effects in some applications, such as subpar performance (which can be mitigated by adjusting the pool size) and/or unrecoverable and catastrophic memory fragmentation.

Compressing HTTP requests and responses#

查看v10.x中文文档

The zlib module can be used to implement support for the gzip, deflate and br 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.

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: 'example.com',
                           path: '/',
                           port: 80,
                           headers: { 'Accept-Encoding': 'br,gzip,deflate' } });
request.on('response', (response) => {
  const output = fs.createWriteStream('example.com_index.html');

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

  // Note: This is not a conformant accept-encoding parser.
  // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
  if (/\bdeflate\b/.test(acceptEncoding)) {
    response.writeHead(200, { 'Content-Encoding': 'deflate' });
    raw.pipe(zlib.createDeflate()).pipe(response);
  } else if (/\bgzip\b/.test(acceptEncoding)) {
    response.writeHead(200, { 'Content-Encoding': 'gzip' });
    raw.pipe(zlib.createGzip()).pipe(response);
  } else if (/\bbr\b/.test(acceptEncoding)) {
    response.writeHead(200, { 'Content-Encoding': 'br' });
    raw.pipe(zlib.createBrotliCompress()).pipe(response);
  } else {
    response.writeHead(200, {});
    raw.pipe(response);
  }
}).listen(1337);

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

zlib.unzip(
  buffer,
  // For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.
  { finishFlush: zlib.constants.Z_SYNC_FLUSH },
  (err, buffer) => {
    if (!err) {
      console.log(buffer.toString());
    } 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#

中英对照提交修改

来自 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 操作 能够处理更多的数据. 所以, 这是另外一个影响速度的因素, 代价是内存的占用.

For zlib-based streams#

暂无中英对照提交修改

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.

For Brotli-based streams#

暂无中英对照提交修改

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.

Flushing#

中英对照提交修改

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

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

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

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

  setInterval(() => {
    output.write(`The current time is ${Date()}\n`, () => {
      // 数据已经传递给了 zlib,但压缩算法看能已经决定缓存数据以便得到更高的压缩效率。
      output.flush();
    });
  }, 1000);
}).listen(1337);

Constants#

中英对照提交修改

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

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

zlib constants#

中英对照提交修改

提供一个列举出 Zlib 相关常数的对象。

Brotli constants#

暂无中英对照提交修改

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

Flush operations#

暂无中英对照提交修改

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.

Compressor options#

暂无中英对照提交修改

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.

Decompressor options#

暂无中英对照提交修改

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).

Class: Options#

中英对照提交修改

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

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

更多信息查阅在 https://zlib.net/manual.html#Advanced 关于 deflateInit2 以及 inflateInit2 的描述,

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

Class: zlib.BrotliCompress#

暂无中英对照提交修改

Compress data using the Brotli algorithm.

Class: zlib.BrotliDecompress#

暂无中英对照提交修改

Decompress data using the Brotli algorithm.

Class: zlib.Deflate#

中英对照提交修改

使用 deflate 压缩数据。

Class: zlib.DeflateRaw#

中英对照提交修改

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

Class: zlib.Gunzip#

中英对照提交修改

解压缩 gzip 流。

Class: zlib.Gzip#

中英对照提交修改

使用 gzip 压缩数据。

Class: zlib.Inflate#

中英对照提交修改

解压一个 deflate 流。

Class: zlib.InflateRaw#

中英对照提交修改

解压一个 raw deflate 流。

Class: zlib.Unzip#

中英对照提交修改

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

Class: zlib.ZlibBase#

暂无中英对照提交修改

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

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

zlib.bytesRead#

中英对照提交修改

zlib.bytesRead 属性指的是压缩引擎处理之前读取的字节数 (压缩或者解压, 适用于派生类)。

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).

zlib.close([callback])#

暂无中英对照提交修改

Close the underlying handle.

zlib.flush([kind, ]callback)#

中英对照提交修改

kind 默认为 zlib.constants.Z_FULL_FLUSH.

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

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

zlib.params(level, strategy, callback)#

中英对照提交修改

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

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])#

查看v10.x中文文档

Creates and returns a new Deflate object.

zlib.createDeflateRaw([options])#

查看v10.x中文文档

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])#

查看v10.x中文文档

Creates and returns a new Gunzip object.

zlib.createGzip([options])#

查看v10.x中文文档

Creates and returns a new Gzip object.

zlib.createInflate([options])#

查看v10.x中文文档

Creates and returns a new Inflate object.

zlib.createInflateRaw([options])#

查看v10.x中文文档

Creates and returns a new InflateRaw object.

zlib.createUnzip([options])#

查看v10.x中文文档

Creates and returns a new Unzip object.

Convenience Methods#

中英对照提交修改

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

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

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])#

查看v10.x中文文档

Compress a chunk of data with Deflate.

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

暂无中英对照提交修改

zlib.deflateRawSync(buffer[, options])#

查看v10.x中文文档

Compress a chunk of data with DeflateRaw.

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

暂无中英对照提交修改

zlib.gunzipSync(buffer[, options])#

查看v10.x中文文档

Decompress a chunk of data with Gunzip.

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

暂无中英对照提交修改

zlib.gzipSync(buffer[, options])#

查看v10.x中文文档

Compress a chunk of data with Gzip.

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

暂无中英对照提交修改

zlib.inflateSync(buffer[, options])#

查看v10.x中文文档

Decompress a chunk of data with Inflate.

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

暂无中英对照提交修改

zlib.inflateRawSync(buffer[, options])#

查看v10.x中文文档

Decompress a chunk of data with InflateRaw.

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

暂无中英对照提交修改

zlib.unzipSync(buffer[, options])#

查看v10.x中文文档

Decompress a chunk of data with Unzip.