{ "source": "doc/api/zlib.md", "modules": [ { "textRaw": "Zlib", "name": "zlib", "stability": 2, "stabilityText": "Stable", "desc": "

The zlib module provides compression functionality implemented using Gzip and\nDeflate/Inflate. It can be accessed using:

\n
const zlib = require('zlib');\n
\n

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

\n
const gzip = zlib.createGzip();\nconst fs = require('fs');\nconst inp = fs.createReadStream('input.txt');\nconst out = fs.createWriteStream('input.txt.gz');\n\ninp.pipe(gzip).pipe(out);\n
\n

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

\n
const input = '.................................';\nzlib.deflate(input, (err, buffer) => {\n  if (!err) {\n    console.log(buffer.toString('base64'));\n  } else {\n    // handle error\n  }\n});\n\nconst buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');\nzlib.unzip(buffer, (err, buffer) => {\n  if (!err) {\n    console.log(buffer.toString());\n  } else {\n    // handle error\n  }\n});\n
\n", "modules": [ { "textRaw": "Compressing HTTP requests and responses", "name": "compressing_http_requests_and_responses", "desc": "

The zlib module can be used to implement support for the gzip and deflate\ncontent-encoding mechanisms defined by\nHTTP.

\n

The HTTP Accept-Encoding header is used within an http request to identify\nthe compression encodings accepted by the client. The Content-Encoding\nheader is used to identify the compression encodings actually applied to a\nmessage.

\n

Note: the examples given below are drastically simplified to show\nthe basic concept. Using zlib encoding can be expensive, and the results\nought to be cached. See Memory Usage Tuning for more information\non the speed/memory/compression tradeoffs involved in zlib usage.

\n
// client request example\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nconst request = http.get({ host: 'example.com',\n                           path: '/',\n                           port: 80,\n                           headers: { 'Accept-Encoding': 'gzip,deflate' } });\nrequest.on('response', (response) => {\n  const output = fs.createWriteStream('example.com_index.html');\n\n  switch (response.headers['content-encoding']) {\n    // or, just use zlib.createUnzip() to handle both cases\n    case 'gzip':\n      response.pipe(zlib.createGunzip()).pipe(output);\n      break;\n    case 'deflate':\n      response.pipe(zlib.createInflate()).pipe(output);\n      break;\n    default:\n      response.pipe(output);\n      break;\n  }\n});\n
\n
// server example\n// Running a gzip operation on every request is quite expensive.\n// It would be much more efficient to cache the compressed buffer.\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nhttp.createServer((request, response) => {\n  const raw = fs.createReadStream('index.html');\n  let acceptEncoding = request.headers['accept-encoding'];\n  if (!acceptEncoding) {\n    acceptEncoding = '';\n  }\n\n  // Note: this is not a conformant accept-encoding parser.\n  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3\n  if (acceptEncoding.match(/\\bdeflate\\b/)) {\n    response.writeHead(200, { 'Content-Encoding': 'deflate' });\n    raw.pipe(zlib.createDeflate()).pipe(response);\n  } else if (acceptEncoding.match(/\\bgzip\\b/)) {\n    response.writeHead(200, { 'Content-Encoding': 'gzip' });\n    raw.pipe(zlib.createGzip()).pipe(response);\n  } else {\n    response.writeHead(200, {});\n    raw.pipe(response);\n  }\n}).listen(1337);\n
\n

By default, the zlib methods will throw an error when decompressing\ntruncated data. However, if it is known that the data is incomplete, or\nthe desire is to inspect only the beginning of a compressed file, it is\npossible to suppress the default error handling by changing the flushing\nmethod that is used to compressed the last chunk of input data:

\n
// This is a truncated version of the buffer from the above examples\nconst buffer = Buffer.from('eJzT0yMA', 'base64');\n\nzlib.unzip(\n  buffer,\n  { finishFlush: zlib.Z_SYNC_FLUSH },\n  (err, buffer) => {\n    if (!err) {\n      console.log(buffer.toString());\n    } else {\n      // handle error\n    }\n  });\n
\n

This will not change the behavior in other error-throwing situations, e.g.\nwhen the input data has an invalid format. Using this method, it will not be\npossible to determine whether the input ended prematurely or lacks the\nintegrity checks, making it necessary to manually check that the\ndecompressed result is valid.

\n", "type": "module", "displayName": "Compressing HTTP requests and responses" }, { "textRaw": "Flushing", "name": "flushing", "desc": "

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

\n

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

\n
const zlib = require('zlib');\nconst http = require('http');\n\nhttp.createServer((request, response) => {\n  // For the sake of simplicity, the Accept-Encoding checks are omitted.\n  response.writeHead(200, { 'content-encoding': 'gzip' });\n  const output = zlib.createGzip();\n  output.pipe(response);\n\n  setInterval(() => {\n    output.write(`The current time is ${Date()}\\n`, () => {\n      // The data has been passed to zlib, but the compression algorithm may\n      // have decided to buffer the data for more efficient compression.\n      // Calling .flush() will make the data available as soon as the client\n      // is ready to receive it.\n      output.flush();\n    });\n  }, 1000);\n}).listen(1337);\n
\n", "type": "module", "displayName": "Flushing" } ], "miscs": [ { "textRaw": "Memory Usage Tuning", "name": "Memory Usage Tuning", "type": "misc", "desc": "

From zlib/zconf.h, modified to node.js's usage:

\n

The memory requirements for deflate are (in bytes):

\n
(1 << (windowBits + 2)) + (1 << (memLevel + 9));\n
\n

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

\n

For example, to reduce the default memory requirements from 256K to 128K, the\noptions should be set to:

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

This will, however, generally degrade compression.

\n

The memory requirements for inflate are (in bytes)

\n
1 << windowBits;\n
\n

That is, 32K for windowBits=15 (default value) plus a few kilobytes\nfor small objects.

\n

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

\n

The speed of zlib compression is affected most dramatically by the\nlevel setting. A higher level will result in better compression, but\nwill take longer to complete. A lower level will result in less\ncompression, but will be much faster.

\n

In general, greater memory usage options will mean that Node.js has to make\nfewer calls to zlib because it will be able to process more data on\neach write operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.

\n" }, { "textRaw": "Constants", "name": "Constants", "meta": { "added": [ "v0.5.8" ] }, "type": "misc", "desc": "

All of the constants defined in zlib.h are also defined on require('zlib').\nIn the normal course of operations, it will not be necessary to use these\nconstants. They are documented so that their presence is not surprising. This\nsection is taken almost directly from the zlib documentation. See\nhttp://zlib.net/manual.html#Constants for more details.

\n

Allowed flush values.

\n\n

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

\n\n

Compression levels.

\n\n

Compression strategy.

\n\n

The deflate compression method (the only one supported in this version).

\n\n

For initializing zalloc, zfree, opaque.

\n\n" }, { "textRaw": "Class Options", "name": "Class Options", "meta": { "added": [ "v0.11.1" ] }, "type": "misc", "desc": "

Each class takes an options object. All options are optional.

\n

Note that some options are only relevant when compressing, and are\nignored by the decompression classes.

\n\n

See the description of deflateInit2 and inflateInit2 at\nhttp://zlib.net/manual.html#Advanced for more information on these.

\n" }, { "textRaw": "Convenience Methods", "name": "Convenience Methods", "type": "misc", "desc": "

All of these take a Buffer or string as the first argument, an optional\nsecond argument to supply options to the zlib classes and will call the\nsupplied callback with callback(error, result).

\n

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

\n", "methods": [ { "textRaw": "zlib.deflate(buf[, options], callback)", "type": "method", "name": "deflate", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Compress a Buffer or string with Deflate.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.deflateSync(buf[, options])", "type": "method", "name": "deflateSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Compress a Buffer or string with Deflate.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.deflateRaw(buf[, options], callback)", "type": "method", "name": "deflateRaw", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Compress a Buffer or string with DeflateRaw.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.deflateRawSync(buf[, options])", "type": "method", "name": "deflateRawSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Compress a Buffer or string with DeflateRaw.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.gunzip(buf[, options], callback)", "type": "method", "name": "gunzip", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Decompress a Buffer or string with Gunzip.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gunzipSync(buf[, options])", "type": "method", "name": "gunzipSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Decompress a Buffer or string with Gunzip.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.gzip(buf[, options], callback)", "type": "method", "name": "gzip", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Compress a Buffer or string with Gzip.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gzipSync(buf[, options])", "type": "method", "name": "gzipSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Compress a Buffer or string with Gzip.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.inflate(buf[, options], callback)", "type": "method", "name": "inflate", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Decompress a Buffer or string with Inflate.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflateSync(buf[, options])", "type": "method", "name": "inflateSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Decompress a Buffer or string with Inflate.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.inflateRaw(buf[, options], callback)", "type": "method", "name": "inflateRaw", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Decompress a Buffer or string with InflateRaw.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflateRawSync(buf[, options])", "type": "method", "name": "inflateRawSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Decompress a Buffer or string with InflateRaw.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.unzip(buf[, options], callback)", "type": "method", "name": "unzip", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Decompress a Buffer or string with Unzip.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.unzipSync(buf[, options])", "type": "method", "name": "unzipSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Decompress a Buffer or string with Unzip.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] } ] } ], "meta": { "added": [ "v0.5.8" ] }, "classes": [ { "textRaw": "Class: zlib.Deflate", "type": "class", "name": "zlib.Deflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Compress data using deflate.

\n" }, { "textRaw": "Class: zlib.DeflateRaw", "type": "class", "name": "zlib.DeflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "

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

\n" }, { "textRaw": "Class: zlib.Gunzip", "type": "class", "name": "zlib.Gunzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Decompress a gzip stream.

\n" }, { "textRaw": "Class: zlib.Gzip", "type": "class", "name": "zlib.Gzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Compress data using gzip.

\n" }, { "textRaw": "Class: zlib.Inflate", "type": "class", "name": "zlib.Inflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Decompress a deflate stream.

\n" }, { "textRaw": "Class: zlib.InflateRaw", "type": "class", "name": "zlib.InflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Decompress a raw deflate stream.

\n" }, { "textRaw": "Class: zlib.Unzip", "type": "class", "name": "zlib.Unzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

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

\n" }, { "textRaw": "Class: zlib.Zlib", "type": "class", "name": "zlib.Zlib", "meta": { "added": [ "v0.5.8" ] }, "desc": "

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

\n", "methods": [ { "textRaw": "zlib.flush([kind], callback)", "type": "method", "name": "flush", "meta": { "added": [ "v0.5.8" ] }, "desc": "

kind defaults to zlib.Z_FULL_FLUSH.

\n

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

\n

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

\n", "signatures": [ { "params": [ { "name": "kind", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.params(level, strategy, callback)", "type": "method", "name": "params", "meta": { "added": [ "v0.11.4" ] }, "desc": "

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

\n", "signatures": [ { "params": [ { "name": "level" }, { "name": "strategy" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.reset()", "type": "method", "name": "reset", "meta": { "added": [ "v0.7.0" ] }, "desc": "

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

\n", "signatures": [ { "params": [] } ] } ] } ], "properties": [ { "textRaw": "zlib.constants", "name": "constants", "meta": { "added": [ "v7.0.0" ] }, "desc": "

Provides an object enumerating Zlib-related constants.

\n" } ], "methods": [ { "textRaw": "zlib.createDeflate([options])", "type": "method", "name": "createDeflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new Deflate object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflateRaw([options])", "type": "method", "name": "createDeflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new DeflateRaw object with an options.

\n

Note: The zlib library rejects requests for 256-byte windows (i.e.,\n{ windowBits: 8 } in options). An Error will be thrown when creating a\nDeflateRaw object with this specific value of the windowBits option.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGunzip([options])", "type": "method", "name": "createGunzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new Gunzip object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGzip([options])", "type": "method", "name": "createGzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new Gzip object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflate([options])", "type": "method", "name": "createInflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new Inflate object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflateRaw([options])", "type": "method", "name": "createInflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new InflateRaw object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createUnzip([options])", "type": "method", "name": "createUnzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new Unzip object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] } ], "type": "module", "displayName": "Zlib" } ] }