Node.js v20.18.0 文档


Zlib#

稳定性: 2 - 稳定的

¥Stability: 2 - Stable

源代码: 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 {
  createReadStream,
  createWriteStream,
} = 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;
  }
  console.log(buffer.toString('base64'));
});

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

// Or, Promisified

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

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

线程池使用和性能注意事项#

¥Threadpool usage and performance considerations

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

// WARNING: DO NOT DO THIS!
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 请求和响应#

¥Compressing HTTP requests and responses

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: '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('An error occurred:', err);
      process.exitCode = 1;
    }
  };

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

  // 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' });
    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 方法在解压缩截断数据时会抛出错误。但是,如果已知数据不完整,或者希望仅检查压缩文件的开头,则可以通过更改用于解压缩输入的最后一个块的刷新方法来抑制默认错误处理数据:

¥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.error('An error occurred:', err);
      process.exitCode = 1;
    }
    console.log(buffer.toString());
  }); 

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

¥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 的流#

¥For zlib-based streams

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 的流#

¥For Brotli-based streams

有与基于 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's level option matches Brotli's BROTLI_PARAM_QUALITY option.

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

    ¥zlib's windowBits option matches Brotli's BROTLI_PARAM_LGWIN option.

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

¥See below for more details on Brotli-specific options.

刷新#

¥Flushing

在压缩流上调用 .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.
      clearInterval(i);
      response.end();
      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.
      output.flush();
    });
  }, 1000);
}).listen(1337); 

常量#

¥Constants

zlib 常量#

¥zlib constants

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 constants

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

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

刷新操作#

¥Flush operations

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

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

  • zlib.constants.BROTLI_OPERATION_PROCESS(所有操作的默认值)

    ¥zlib.constants.BROTLI_OPERATION_PROCESS (default for all operations)

  • zlib.constants.BROTLI_OPERATION_FLUSH(调用 .flush() 时默认)

    ¥zlib.constants.BROTLI_OPERATION_FLUSH (default when calling .flush())

  • zlib.constants.BROTLI_OPERATION_FINISH(最后一个块的默认值)

    ¥zlib.constants.BROTLI_OPERATION_FINISH (default for the last chunk)

  • zlib.constants.BROTLI_OPERATION_EMIT_METADATA

    • 这个特定的操作可能很难在 Node.js 上下文中使用,因为流层很难知道哪些数据会在这个帧中结束。此外,目前无法通过 Node.js API 使用这些数据。

      ¥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

可以在 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_PARAM_MODE

    • BROTLI_MODE_GENERIC(默认)

      ¥BROTLI_MODE_GENERIC (default)

    • BROTLI_MODE_TEXT,针对 UTF-8 文本进行了调整

      ¥BROTLI_MODE_TEXT, adjusted for UTF-8 text

    • BROTLI_MODE_FONT,针对 WOFF 2.0 字体进行了调整

      ¥BROTLI_MODE_FONT, adjusted for WOFF 2.0 fonts

  • BROTLI_PARAM_QUALITY

    • 范围从 BROTLI_MIN_QUALITYBROTLI_MAX_QUALITY,默认为 BROTLI_DEFAULT_QUALITY

      ¥Ranges from BROTLI_MIN_QUALITY to BROTLI_MAX_QUALITY, with a default of BROTLI_DEFAULT_QUALITY.

  • BROTLI_PARAM_SIZE_HINT

    • 表示预期输入大小的整数值;对于未知的输入大小,默认为 0

      ¥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

    • 范围从 BROTLI_MIN_WINDOW_BITSBROTLI_MAX_WINDOW_BITS,默认为 BROTLI_DEFAULT_WINDOW,如果设置了 BROTLI_PARAM_LARGE_WINDOW 标志,则最高可达 BROTLI_LARGE_MAX_WINDOW_BITS

      ¥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

    • 范围从 BROTLI_MIN_INPUT_BLOCK_BITSBROTLI_MAX_INPUT_BLOCK_BITS

      ¥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

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

      ¥Boolean flag enabling “Large Window Brotli” mode (not compatible with the Brotli format as standardized in RFC 7932).

  • BROTLI_PARAM_NPOSTFIX

    • 范围从 0BROTLI_MAX_NPOSTFIX

      ¥Ranges from 0 to BROTLI_MAX_NPOSTFIX.

  • BROTLI_PARAM_NDIRECT

    • 范围从 015 << NPOSTFIX,步长为 1 << NPOSTFIX

      ¥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

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

      ¥Boolean flag enabling “Large Window Brotli” mode (not compatible with the Brotli format as standardized in RFC 7932).

类:Options#

¥Class: Options

每个基于 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.

类:BrotliOptions#

¥Class: BrotliOptions

每个基于 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,
  },
}); 

类:zlib.BrotliCompress#

¥Class: zlib.BrotliCompress

使用 Brotli 算法压缩数据。

¥Compress data using the Brotli algorithm.

类:zlib.BrotliDecompress#

¥Class: zlib.BrotliDecompress

使用 Brotli 算法解压缩数据。

¥Decompress data using the Brotli algorithm.

类:zlib.Deflate#

¥Class: zlib.Deflate

使用 deflate 压缩数据。

¥Compress data using deflate.

类:zlib.DeflateRaw#

¥Class: zlib.DeflateRaw

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

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

类:zlib.Gunzip#

¥Class: zlib.Gunzip

解压缩 gzip 流。

¥Decompress a gzip stream.

类:zlib.Gzip#

¥Class: zlib.Gzip

使用 gzip 压缩数据。

¥Compress data using gzip.

类:zlib.Inflate#

¥Class: zlib.Inflate

解压缩 deflate 流。

¥Decompress a deflate stream.

类:zlib.InflateRaw#

¥Class: zlib.InflateRaw

解压缩原始的 deflate 流。

¥Decompress a raw deflate stream.

类:zlib.Unzip#

¥Class: zlib.Unzip

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

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

类:zlib.ZlibBase#

¥Class: zlib.ZlibBase

不是由 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.

zlib.bytesRead#

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

¥Stability: 0 - Deprecated: Use zlib.bytesWritten instead.

弃用的 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#

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.crc32(data[, value])#

  • data <string> | <Buffer> | <TypedArray> | <DataView>data 是字符串时,在用于计算之前将其编码为 UTF-8。

    ¥data <string> | <Buffer> | <TypedArray> | <DataView> When data is a string, it will be encoded as UTF-8 before being used for computation.

  • value <integer> 可选的起始值。它必须是 32 位无符号整数。默认值:0

    ¥value <integer> An optional starting value. It must be a 32-bit unsigned integer. Default: 0

  • 返回:<integer> 包含校验和的 32 位无符号整数。

    ¥Returns: <integer> A 32-bit unsigned integer containing the checksum.

计算 data 的 32 位 循环冗余校验 校验和。如果指定了 value,则作为校验和的起始值,否则使用 0 作为起始值。

¥Computes a 32-bit Cyclic Redundancy Check checksum of data. If value is specified, it is used as the starting value of the checksum, otherwise, 0 is used as the starting value.

CRC 算法旨在计算校验和并检测数据传输中的错误。它不适合加密身份验证。

¥The CRC algorithm is designed to compute checksums and to detect error in data transmission. It's not suitable for cryptographic authentication.

为了与其他 API 保持一致,如果 data 是字符串,则会先进行 UTF-8 编码后再用于计算。如果用户仅使用 Node.js 来计算和匹配校验和,则这与默认使用 UTF-8 编码的其他 API 配合良好。

¥To be consistent with other APIs, if the data is a string, it will be encoded with UTF-8 before being used for computation. If users only use Node.js to compute and match the checksums, this works well with other APIs that uses the UTF-8 encoding by default.

一些第三方 JavaScript 库根据 str.charCodeAt() 计算字符串的校验和,以便它可以在浏览器中运行。如果用户想要在浏览器中匹配使用此类库计算的校验和,那么最好在 Node.js 中使用相同的库(如果它也在 Node.js 中运行)。如果用户必须使用 zlib.crc32() 来匹配此类第三方库生成的校验和:

¥Some third-party JavaScript libraries compute the checksum on a string based on str.charCodeAt() so that it can be run in browsers. If users want to match the checksum computed with this kind of library in the browser, it's better to use the same library in Node.js if it also runs in Node.js. If users have to use zlib.crc32() to match the checksum produced by such a third-party library:

  1. 如果库接受 Uint8Array 作为输入,则在浏览器中使用 TextEncoder 将字符串编码为 UTF-8 编码的 Uint8Array,并根据浏览器中的 UTF-8 编码字符串计算校验和。

    ¥If the library accepts Uint8Array as input, use TextEncoder in the browser to encode the string into a Uint8Array with UTF-8 encoding, and compute the checksum based on the UTF-8 encoded string in the browser.

  2. 如果库只接受字符串并根据 str.charCodeAt() 计算数据,则在 Node.js 端,使用 Buffer.from(str, 'utf16le') 将字符串转换为缓冲区。

    ¥If the library only takes a string and compute the data based on str.charCodeAt(), on the Node.js side, convert the string into a buffer using Buffer.from(str, 'utf16le').

import zlib from 'node:zlib';
import { Buffer } from 'node:buffer';

let crc = zlib.crc32('hello');  // 907060870
crc = zlib.crc32('world', crc);  // 4192936109

crc = zlib.crc32(Buffer.from('hello', 'utf16le'));  // 1427272415
crc = zlib.crc32(Buffer.from('world', 'utf16le'), crc);  // 4150509955const zlib = require('node:zlib');
const { Buffer } = require('node:buffer');

let crc = zlib.crc32('hello');  // 907060870
crc = zlib.crc32('world', crc);  // 4192936109

crc = zlib.crc32(Buffer.from('hello', 'utf16le'));  // 1427272415
crc = zlib.crc32(Buffer.from('world', 'utf16le'), crc);  // 4150509955

zlib.close([callback])#

关闭底层句柄。

¥Close the underlying handle.

zlib.flush([kind, ]callback)#

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

    ¥kind Default: zlib.constants.Z_FULL_FLUSH for zlib-based streams, zlib.constants.BROTLI_OPERATION_FLUSH for Brotli-based streams.

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

zlib.reset()#

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

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

zlib.constants#

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

¥Provides an object enumerating Zlib-related constants.

zlib.createBrotliCompress([options])#

创建并返回新的 BrotliCompress 对象。

¥Creates and returns a new BrotliCompress object.

zlib.createBrotliDecompress([options])#

创建并返回新的 BrotliDecompress 对象。

¥Creates and returns a new BrotliDecompress object.

zlib.createDeflate([options])#

创建并返回新的 Deflate 对象。

¥Creates and returns a new Deflate object.

zlib.createDeflateRaw([options])#

创建并返回新的 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.

zlib.createGunzip([options])#

创建并返回新的 Gunzip 对象。

¥Creates and returns a new Gunzip object.

zlib.createGzip([options])#

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

¥Creates and returns a new Gzip object. See example.

zlib.createInflate([options])#

创建并返回新的 Inflate 对象。

¥Creates and returns a new Inflate object.

zlib.createInflateRaw([options])#

创建并返回新的 InflateRaw 对象。

¥Creates and returns a new InflateRaw object.

zlib.createUnzip([options])#

创建并返回新的 Unzip 对象。

¥Creates and returns a new Unzip object.

便捷方法#

¥Convenience methods

所有这些都将 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.

Node.js 中文网 - 粤ICP备13048890号