home / documentation / v19 / zlib

Zlib

目录

Added in: v0.10.0

稳定性: 2 - Stable

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

To access it:

JS

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

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:

JS

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

JS

Threadpool usage and performance considerations

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.

JS

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.

Compressing HTTP requests and responses

The node: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.

JS
JS

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:

JS

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

For zlib-based streams

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

The memory requirements for deflate are (in bytes):

JS

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:

JS

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

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.

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

JS

Constants

Added in: v0.5.8

zlib constants

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.

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 constants

Added in: v11.7.0, v10.16.0

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

C Options

历史
版本更改
v14.5.0, v12.19.0The `maxOutputLength` option is supported now.
v9.4.0The `dictionary` option can be an `ArrayBuffer`.
v8.0.0The `dictionary` option can be an `Uint8Array` now.
v5.11.0The `finishFlush` option is supported now.
v0.11.1Added in: v0.11.1

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.

See the deflateInit2 and inflateInit2 documentation for more information.

C BrotliOptions

历史
版本更改
v14.5.0, v12.19.0The `maxOutputLength` option is supported now.
v11.7.0Added in: v11.7.0

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

For example:

JS

C zlib.BrotliCompress

Added in: v11.7.0, v10.16.0

Compress data using the Brotli algorithm.

C zlib.BrotliDecompress

Added in: v11.7.0, v10.16.0

Decompress data using the Brotli algorithm.

C zlib.Deflate

Added in: v0.5.8

Compress data using deflate.

C zlib.DeflateRaw

Added in: v0.5.8

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

C zlib.Gunzip

历史
版本更改
v6.0.0Trailing garbage at the end of the input stream will now result in an `'error'` event.
v5.9.0Multiple concatenated gzip file members are supported now.
v5.0.0A truncated input stream will now result in an `'error'` event.
v0.5.8Added in: v0.5.8

Decompress a gzip stream.

C zlib.Gzip

Added in: v0.5.8

Compress data using gzip.

C zlib.Inflate

历史
版本更改
v5.0.0A truncated input stream will now result in an `'error'` event.
v0.5.8Added in: v0.5.8

Decompress a deflate stream.

C zlib.InflateRaw

历史
版本更改
v6.8.0Custom dictionaries are now supported by `InflateRaw`.
v5.0.0A truncated input stream will now result in an `'error'` event.
v0.5.8Added in: v0.5.8

Decompress a raw deflate stream.

C zlib.Unzip

Added in: v0.5.8

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

C zlib.ZlibBase

历史
版本更改
v11.7.0, v10.16.0This class was renamed from `Zlib` to `ZlibBase`.
v0.5.8Added in: v0.5.8

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

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

M zlib.bytesRead

Deprecated in: v10.0.0

稳定性: 0 - Deprecated: Use `zlib.bytesWritten` instead.

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.

M zlib.bytesWritten

Added in: v10.0.0

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

M zlib.close([callback])

Added in: v0.9.4

Close the underlying handle.

M zlib.flush([kind, ]callback)

Added in: v0.5.8

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

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.

M zlib.params(level, strategy, callback)

Added in: v0.11.4

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

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

M zlib.reset()

Added in: v0.7.0

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

M zlib.constants

Added in: v7.0.0

Provides an object enumerating Zlib-related constants.

M zlib.createBrotliCompress([options])

Added in: v11.7.0, v10.16.0

Creates and returns a new BrotliCompress object.

M zlib.createBrotliDecompress([options])

Added in: v11.7.0, v10.16.0

Creates and returns a new BrotliDecompress object.

M zlib.createDeflate([options])

Added in: v0.5.8

Creates and returns a new Deflate object.

M zlib.createDeflateRaw([options])

Added in: v0.5.8

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.

M zlib.createGunzip([options])

Added in: v0.5.8

Creates and returns a new Gunzip object.

M zlib.createGzip([options])

Added in: v0.5.8

Creates and returns a new Gzip object. See example.

M zlib.createInflate([options])

Added in: v0.5.8

Creates and returns a new Inflate object.

M zlib.createInflateRaw([options])

Added in: v0.5.8

Creates and returns a new InflateRaw object.

M zlib.createUnzip([options])

Added in: v0.5.8

Creates and returns a new Unzip object.

Convenience methods

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

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

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

Added in: v11.7.0, v10.16.0

M zlib.brotliCompressSync(buffer[, options])

Added in: v11.7.0, v10.16.0

Compress a chunk of data with BrotliCompress.

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

Added in: v11.7.0, v10.16.0

M zlib.brotliDecompressSync(buffer[, options])

Added in: v11.7.0, v10.16.0

Decompress a chunk of data with BrotliDecompress.

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

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.6.0Added in: v0.6.0

M zlib.deflateSync(buffer[, options])

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.11.12Added in: v0.11.12

Compress a chunk of data with Deflate.

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

历史
版本更改
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.6.0Added in: v0.6.0

M zlib.deflateRawSync(buffer[, options])

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.11.12Added in: v0.11.12

Compress a chunk of data with DeflateRaw.

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

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.6.0Added in: v0.6.0

M zlib.gunzipSync(buffer[, options])

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.11.12Added in: v0.11.12

Decompress a chunk of data with Gunzip.

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

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.6.0Added in: v0.6.0

M zlib.gzipSync(buffer[, options])

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.11.12Added in: v0.11.12

Compress a chunk of data with Gzip.

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

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.6.0Added in: v0.6.0

M zlib.inflateSync(buffer[, options])

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.11.12Added in: v0.11.12

Decompress a chunk of data with Inflate.

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

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.6.0Added in: v0.6.0

M zlib.inflateRawSync(buffer[, options])

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.11.12Added in: v0.11.12

Decompress a chunk of data with InflateRaw.

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

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.6.0Added in: v0.6.0

M zlib.unzipSync(buffer[, options])

历史
版本更改
v9.4.0The `buffer` parameter can be an `ArrayBuffer`.
v8.0.0The `buffer` parameter can be any `TypedArray` or `DataView`.
v8.0.0The `buffer` parameter can be an `Uint8Array` now.
v0.11.12Added in: v0.11.12

Decompress a chunk of data with Unzip.