xref: /third_party/node/doc/api/zlib.md (revision 1cb0ef41)
1# Zlib
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/zlib.js -->
8
9The `node:zlib` module provides compression functionality implemented using
10Gzip, Deflate/Inflate, and Brotli.
11
12To access it:
13
14```js
15const zlib = require('node:zlib');
16```
17
18Compression and decompression are built around the Node.js [Streams API][].
19
20Compressing or decompressing a stream (such as a file) can be accomplished by
21piping the source stream through a `zlib` `Transform` stream into a destination
22stream:
23
24```js
25const { createGzip } = require('node:zlib');
26const { pipeline } = require('node:stream');
27const {
28  createReadStream,
29  createWriteStream,
30} = require('node:fs');
31
32const gzip = createGzip();
33const source = createReadStream('input.txt');
34const destination = createWriteStream('input.txt.gz');
35
36pipeline(source, gzip, destination, (err) => {
37  if (err) {
38    console.error('An error occurred:', err);
39    process.exitCode = 1;
40  }
41});
42
43// Or, Promisified
44
45const { promisify } = require('node:util');
46const pipe = promisify(pipeline);
47
48async function do_gzip(input, output) {
49  const gzip = createGzip();
50  const source = createReadStream(input);
51  const destination = createWriteStream(output);
52  await pipe(source, gzip, destination);
53}
54
55do_gzip('input.txt', 'input.txt.gz')
56  .catch((err) => {
57    console.error('An error occurred:', err);
58    process.exitCode = 1;
59  });
60```
61
62It is also possible to compress or decompress data in a single step:
63
64```js
65const { deflate, unzip } = require('node:zlib');
66
67const input = '.................................';
68deflate(input, (err, buffer) => {
69  if (err) {
70    console.error('An error occurred:', err);
71    process.exitCode = 1;
72  }
73  console.log(buffer.toString('base64'));
74});
75
76const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
77unzip(buffer, (err, buffer) => {
78  if (err) {
79    console.error('An error occurred:', err);
80    process.exitCode = 1;
81  }
82  console.log(buffer.toString());
83});
84
85// Or, Promisified
86
87const { promisify } = require('node:util');
88const do_unzip = promisify(unzip);
89
90do_unzip(buffer)
91  .then((buf) => console.log(buf.toString()))
92  .catch((err) => {
93    console.error('An error occurred:', err);
94    process.exitCode = 1;
95  });
96```
97
98## Threadpool usage and performance considerations
99
100All `zlib` APIs, except those that are explicitly synchronous, use the Node.js
101internal threadpool. This can lead to surprising effects and performance
102limitations in some applications.
103
104Creating and using a large number of zlib objects simultaneously can cause
105significant memory fragmentation.
106
107```js
108const zlib = require('node:zlib');
109
110const payload = Buffer.from('This is some data');
111
112// WARNING: DO NOT DO THIS!
113for (let i = 0; i < 30000; ++i) {
114  zlib.deflate(payload, (err, buffer) => {});
115}
116```
117
118In the preceding example, 30,000 deflate instances are created concurrently.
119Because of how some operating systems handle memory allocation and
120deallocation, this may lead to significant memory fragmentation.
121
122It is strongly recommended that the results of compression
123operations be cached to avoid duplication of effort.
124
125## Compressing HTTP requests and responses
126
127The `node:zlib` module can be used to implement support for the `gzip`, `deflate`
128and `br` content-encoding mechanisms defined by
129[HTTP](https://tools.ietf.org/html/rfc7230#section-4.2).
130
131The HTTP [`Accept-Encoding`][] header is used within an HTTP request to identify
132the compression encodings accepted by the client. The [`Content-Encoding`][]
133header is used to identify the compression encodings actually applied to a
134message.
135
136The examples given below are drastically simplified to show the basic concept.
137Using `zlib` encoding can be expensive, and the results ought to be cached.
138See [Memory usage tuning][] for more information on the speed/memory/compression
139tradeoffs involved in `zlib` usage.
140
141```js
142// Client request example
143const zlib = require('node:zlib');
144const http = require('node:http');
145const fs = require('node:fs');
146const { pipeline } = require('node:stream');
147
148const request = http.get({ host: 'example.com',
149                           path: '/',
150                           port: 80,
151                           headers: { 'Accept-Encoding': 'br,gzip,deflate' } });
152request.on('response', (response) => {
153  const output = fs.createWriteStream('example.com_index.html');
154
155  const onError = (err) => {
156    if (err) {
157      console.error('An error occurred:', err);
158      process.exitCode = 1;
159    }
160  };
161
162  switch (response.headers['content-encoding']) {
163    case 'br':
164      pipeline(response, zlib.createBrotliDecompress(), output, onError);
165      break;
166    // Or, just use zlib.createUnzip() to handle both of the following cases:
167    case 'gzip':
168      pipeline(response, zlib.createGunzip(), output, onError);
169      break;
170    case 'deflate':
171      pipeline(response, zlib.createInflate(), output, onError);
172      break;
173    default:
174      pipeline(response, output, onError);
175      break;
176  }
177});
178```
179
180```js
181// server example
182// Running a gzip operation on every request is quite expensive.
183// It would be much more efficient to cache the compressed buffer.
184const zlib = require('node:zlib');
185const http = require('node:http');
186const fs = require('node:fs');
187const { pipeline } = require('node:stream');
188
189http.createServer((request, response) => {
190  const raw = fs.createReadStream('index.html');
191  // Store both a compressed and an uncompressed version of the resource.
192  response.setHeader('Vary', 'Accept-Encoding');
193  let acceptEncoding = request.headers['accept-encoding'];
194  if (!acceptEncoding) {
195    acceptEncoding = '';
196  }
197
198  const onError = (err) => {
199    if (err) {
200      // If an error occurs, there's not much we can do because
201      // the server has already sent the 200 response code and
202      // some amount of data has already been sent to the client.
203      // The best we can do is terminate the response immediately
204      // and log the error.
205      response.end();
206      console.error('An error occurred:', err);
207    }
208  };
209
210  // Note: This is not a conformant accept-encoding parser.
211  // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
212  if (/\bdeflate\b/.test(acceptEncoding)) {
213    response.writeHead(200, { 'Content-Encoding': 'deflate' });
214    pipeline(raw, zlib.createDeflate(), response, onError);
215  } else if (/\bgzip\b/.test(acceptEncoding)) {
216    response.writeHead(200, { 'Content-Encoding': 'gzip' });
217    pipeline(raw, zlib.createGzip(), response, onError);
218  } else if (/\bbr\b/.test(acceptEncoding)) {
219    response.writeHead(200, { 'Content-Encoding': 'br' });
220    pipeline(raw, zlib.createBrotliCompress(), response, onError);
221  } else {
222    response.writeHead(200, {});
223    pipeline(raw, response, onError);
224  }
225}).listen(1337);
226```
227
228By default, the `zlib` methods will throw an error when decompressing
229truncated data. However, if it is known that the data is incomplete, or
230the desire is to inspect only the beginning of a compressed file, it is
231possible to suppress the default error handling by changing the flushing
232method that is used to decompress the last chunk of input data:
233
234```js
235// This is a truncated version of the buffer from the above examples
236const buffer = Buffer.from('eJzT0yMA', 'base64');
237
238zlib.unzip(
239  buffer,
240  // For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.
241  { finishFlush: zlib.constants.Z_SYNC_FLUSH },
242  (err, buffer) => {
243    if (err) {
244      console.error('An error occurred:', err);
245      process.exitCode = 1;
246    }
247    console.log(buffer.toString());
248  });
249```
250
251This will not change the behavior in other error-throwing situations, e.g.
252when the input data has an invalid format. Using this method, it will not be
253possible to determine whether the input ended prematurely or lacks the
254integrity checks, making it necessary to manually check that the
255decompressed result is valid.
256
257## Memory usage tuning
258
259<!--type=misc-->
260
261### For zlib-based streams
262
263From `zlib/zconf.h`, modified for Node.js usage:
264
265The memory requirements for deflate are (in bytes):
266
267<!-- eslint-disable semi -->
268
269```js
270(1 << (windowBits + 2)) + (1 << (memLevel + 9))
271```
272
273That is: 128K for `windowBits` = 15 + 128K for `memLevel` = 8
274(default values) plus a few kilobytes for small objects.
275
276For example, to reduce the default memory requirements from 256K to 128K, the
277options should be set to:
278
279```js
280const options = { windowBits: 14, memLevel: 7 };
281```
282
283This will, however, generally degrade compression.
284
285The memory requirements for inflate are (in bytes) `1 << windowBits`.
286That is, 32K for `windowBits` = 15 (default value) plus a few kilobytes
287for small objects.
288
289This is in addition to a single internal output slab buffer of size
290`chunkSize`, which defaults to 16K.
291
292The speed of `zlib` compression is affected most dramatically by the
293`level` setting. A higher level will result in better compression, but
294will take longer to complete. A lower level will result in less
295compression, but will be much faster.
296
297In general, greater memory usage options will mean that Node.js has to make
298fewer calls to `zlib` because it will be able to process more data on
299each `write` operation. So, this is another factor that affects the
300speed, at the cost of memory usage.
301
302### For Brotli-based streams
303
304There are equivalents to the zlib options for Brotli-based streams, although
305these options have different ranges than the zlib ones:
306
307* zlib's `level` option matches Brotli's `BROTLI_PARAM_QUALITY` option.
308* zlib's `windowBits` option matches Brotli's `BROTLI_PARAM_LGWIN` option.
309
310See [below][Brotli parameters] for more details on Brotli-specific options.
311
312## Flushing
313
314Calling [`.flush()`][] on a compression stream will make `zlib` return as much
315output as currently possible. This may come at the cost of degraded compression
316quality, but can be useful when data needs to be available as soon as possible.
317
318In the following example, `flush()` is used to write a compressed partial
319HTTP response to the client:
320
321```js
322const zlib = require('node:zlib');
323const http = require('node:http');
324const { pipeline } = require('node:stream');
325
326http.createServer((request, response) => {
327  // For the sake of simplicity, the Accept-Encoding checks are omitted.
328  response.writeHead(200, { 'content-encoding': 'gzip' });
329  const output = zlib.createGzip();
330  let i;
331
332  pipeline(output, response, (err) => {
333    if (err) {
334      // If an error occurs, there's not much we can do because
335      // the server has already sent the 200 response code and
336      // some amount of data has already been sent to the client.
337      // The best we can do is terminate the response immediately
338      // and log the error.
339      clearInterval(i);
340      response.end();
341      console.error('An error occurred:', err);
342    }
343  });
344
345  i = setInterval(() => {
346    output.write(`The current time is ${Date()}\n`, () => {
347      // The data has been passed to zlib, but the compression algorithm may
348      // have decided to buffer the data for more efficient compression.
349      // Calling .flush() will make the data available as soon as the client
350      // is ready to receive it.
351      output.flush();
352    });
353  }, 1000);
354}).listen(1337);
355```
356
357## Constants
358
359<!-- YAML
360added: v0.5.8
361-->
362
363<!--type=misc-->
364
365### zlib constants
366
367All of the constants defined in `zlib.h` are also defined on
368`require('node:zlib').constants`. In the normal course of operations, it will
369not be necessary to use these constants. They are documented so that their
370presence is not surprising. This section is taken almost directly from the
371[zlib documentation][].
372
373Previously, the constants were available directly from `require('node:zlib')`,
374for instance `zlib.Z_NO_FLUSH`. Accessing the constants directly from the module
375is currently still possible but is deprecated.
376
377Allowed flush values.
378
379* `zlib.constants.Z_NO_FLUSH`
380* `zlib.constants.Z_PARTIAL_FLUSH`
381* `zlib.constants.Z_SYNC_FLUSH`
382* `zlib.constants.Z_FULL_FLUSH`
383* `zlib.constants.Z_FINISH`
384* `zlib.constants.Z_BLOCK`
385* `zlib.constants.Z_TREES`
386
387Return codes for the compression/decompression functions. Negative
388values are errors, positive values are used for special but normal
389events.
390
391* `zlib.constants.Z_OK`
392* `zlib.constants.Z_STREAM_END`
393* `zlib.constants.Z_NEED_DICT`
394* `zlib.constants.Z_ERRNO`
395* `zlib.constants.Z_STREAM_ERROR`
396* `zlib.constants.Z_DATA_ERROR`
397* `zlib.constants.Z_MEM_ERROR`
398* `zlib.constants.Z_BUF_ERROR`
399* `zlib.constants.Z_VERSION_ERROR`
400
401Compression levels.
402
403* `zlib.constants.Z_NO_COMPRESSION`
404* `zlib.constants.Z_BEST_SPEED`
405* `zlib.constants.Z_BEST_COMPRESSION`
406* `zlib.constants.Z_DEFAULT_COMPRESSION`
407
408Compression strategy.
409
410* `zlib.constants.Z_FILTERED`
411* `zlib.constants.Z_HUFFMAN_ONLY`
412* `zlib.constants.Z_RLE`
413* `zlib.constants.Z_FIXED`
414* `zlib.constants.Z_DEFAULT_STRATEGY`
415
416### Brotli constants
417
418<!-- YAML
419added:
420 - v11.7.0
421 - v10.16.0
422-->
423
424There are several options and other constants available for Brotli-based
425streams:
426
427#### Flush operations
428
429The following values are valid flush operations for Brotli-based streams:
430
431* `zlib.constants.BROTLI_OPERATION_PROCESS` (default for all operations)
432* `zlib.constants.BROTLI_OPERATION_FLUSH` (default when calling `.flush()`)
433* `zlib.constants.BROTLI_OPERATION_FINISH` (default for the last chunk)
434* `zlib.constants.BROTLI_OPERATION_EMIT_METADATA`
435  * This particular operation may be hard to use in a Node.js context,
436    as the streaming layer makes it hard to know which data will end up
437    in this frame. Also, there is currently no way to consume this data through
438    the Node.js API.
439
440#### Compressor options
441
442There are several options that can be set on Brotli encoders, affecting
443compression efficiency and speed. Both the keys and the values can be accessed
444as properties of the `zlib.constants` object.
445
446The most important options are:
447
448* `BROTLI_PARAM_MODE`
449  * `BROTLI_MODE_GENERIC` (default)
450  * `BROTLI_MODE_TEXT`, adjusted for UTF-8 text
451  * `BROTLI_MODE_FONT`, adjusted for WOFF 2.0 fonts
452* `BROTLI_PARAM_QUALITY`
453  * Ranges from `BROTLI_MIN_QUALITY` to `BROTLI_MAX_QUALITY`,
454    with a default of `BROTLI_DEFAULT_QUALITY`.
455* `BROTLI_PARAM_SIZE_HINT`
456  * Integer value representing the expected input size;
457    defaults to `0` for an unknown input size.
458
459The following flags can be set for advanced control over the compression
460algorithm and memory usage tuning:
461
462* `BROTLI_PARAM_LGWIN`
463  * Ranges from `BROTLI_MIN_WINDOW_BITS` to `BROTLI_MAX_WINDOW_BITS`,
464    with a default of `BROTLI_DEFAULT_WINDOW`, or up to
465    `BROTLI_LARGE_MAX_WINDOW_BITS` if the `BROTLI_PARAM_LARGE_WINDOW` flag
466    is set.
467* `BROTLI_PARAM_LGBLOCK`
468  * Ranges from `BROTLI_MIN_INPUT_BLOCK_BITS` to `BROTLI_MAX_INPUT_BLOCK_BITS`.
469* `BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING`
470  * Boolean flag that decreases compression ratio in favour of
471    decompression speed.
472* `BROTLI_PARAM_LARGE_WINDOW`
473  * Boolean flag enabling “Large Window Brotli” mode (not compatible with the
474    Brotli format as standardized in [RFC 7932][]).
475* `BROTLI_PARAM_NPOSTFIX`
476  * Ranges from `0` to `BROTLI_MAX_NPOSTFIX`.
477* `BROTLI_PARAM_NDIRECT`
478  * Ranges from `0` to `15 << NPOSTFIX` in steps of `1 << NPOSTFIX`.
479
480#### Decompressor options
481
482These advanced options are available for controlling decompression:
483
484* `BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION`
485  * Boolean flag that affects internal memory allocation patterns.
486* `BROTLI_DECODER_PARAM_LARGE_WINDOW`
487  * Boolean flag enabling “Large Window Brotli” mode (not compatible with the
488    Brotli format as standardized in [RFC 7932][]).
489
490## Class: `Options`
491
492<!-- YAML
493added: v0.11.1
494changes:
495  - version:
496    - v14.5.0
497    - v12.19.0
498    pr-url: https://github.com/nodejs/node/pull/33516
499    description: The `maxOutputLength` option is supported now.
500  - version: v9.4.0
501    pr-url: https://github.com/nodejs/node/pull/16042
502    description: The `dictionary` option can be an `ArrayBuffer`.
503  - version: v8.0.0
504    pr-url: https://github.com/nodejs/node/pull/12001
505    description: The `dictionary` option can be an `Uint8Array` now.
506  - version: v5.11.0
507    pr-url: https://github.com/nodejs/node/pull/6069
508    description: The `finishFlush` option is supported now.
509-->
510
511<!--type=misc-->
512
513Each zlib-based class takes an `options` object. No options are required.
514
515Some options are only relevant when compressing and are
516ignored by the decompression classes.
517
518* `flush` {integer} **Default:** `zlib.constants.Z_NO_FLUSH`
519* `finishFlush` {integer} **Default:** `zlib.constants.Z_FINISH`
520* `chunkSize` {integer} **Default:** `16 * 1024`
521* `windowBits` {integer}
522* `level` {integer} (compression only)
523* `memLevel` {integer} (compression only)
524* `strategy` {integer} (compression only)
525* `dictionary` {Buffer|TypedArray|DataView|ArrayBuffer} (deflate/inflate only,
526  empty dictionary by default)
527* `info` {boolean} (If `true`, returns an object with `buffer` and `engine`.)
528* `maxOutputLength` {integer} Limits output size when using
529  [convenience methods][]. **Default:** [`buffer.kMaxLength`][]
530
531See the [`deflateInit2` and `inflateInit2`][] documentation for more
532information.
533
534## Class: `BrotliOptions`
535
536<!-- YAML
537added: v11.7.0
538changes:
539  - version:
540    - v14.5.0
541    - v12.19.0
542    pr-url: https://github.com/nodejs/node/pull/33516
543    description: The `maxOutputLength` option is supported now.
544-->
545
546<!--type=misc-->
547
548Each Brotli-based class takes an `options` object. All options are optional.
549
550* `flush` {integer} **Default:** `zlib.constants.BROTLI_OPERATION_PROCESS`
551* `finishFlush` {integer} **Default:** `zlib.constants.BROTLI_OPERATION_FINISH`
552* `chunkSize` {integer} **Default:** `16 * 1024`
553* `params` {Object} Key-value object containing indexed [Brotli parameters][].
554* `maxOutputLength` {integer} Limits output size when using
555  [convenience methods][]. **Default:** [`buffer.kMaxLength`][]
556
557For example:
558
559```js
560const stream = zlib.createBrotliCompress({
561  chunkSize: 32 * 1024,
562  params: {
563    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
564    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,
565    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size,
566  },
567});
568```
569
570## Class: `zlib.BrotliCompress`
571
572<!-- YAML
573added:
574 - v11.7.0
575 - v10.16.0
576-->
577
578Compress data using the Brotli algorithm.
579
580## Class: `zlib.BrotliDecompress`
581
582<!-- YAML
583added:
584 - v11.7.0
585 - v10.16.0
586-->
587
588Decompress data using the Brotli algorithm.
589
590## Class: `zlib.Deflate`
591
592<!-- YAML
593added: v0.5.8
594-->
595
596Compress data using deflate.
597
598## Class: `zlib.DeflateRaw`
599
600<!-- YAML
601added: v0.5.8
602-->
603
604Compress data using deflate, and do not append a `zlib` header.
605
606## Class: `zlib.Gunzip`
607
608<!-- YAML
609added: v0.5.8
610changes:
611  - version: v6.0.0
612    pr-url: https://github.com/nodejs/node/pull/5883
613    description: Trailing garbage at the end of the input stream will now
614                 result in an `'error'` event.
615  - version: v5.9.0
616    pr-url: https://github.com/nodejs/node/pull/5120
617    description: Multiple concatenated gzip file members are supported now.
618  - version: v5.0.0
619    pr-url: https://github.com/nodejs/node/pull/2595
620    description: A truncated input stream will now result in an `'error'` event.
621-->
622
623Decompress a gzip stream.
624
625## Class: `zlib.Gzip`
626
627<!-- YAML
628added: v0.5.8
629-->
630
631Compress data using gzip.
632
633## Class: `zlib.Inflate`
634
635<!-- YAML
636added: v0.5.8
637changes:
638  - version: v5.0.0
639    pr-url: https://github.com/nodejs/node/pull/2595
640    description: A truncated input stream will now result in an `'error'` event.
641-->
642
643Decompress a deflate stream.
644
645## Class: `zlib.InflateRaw`
646
647<!-- YAML
648added: v0.5.8
649changes:
650  - version: v6.8.0
651    pr-url: https://github.com/nodejs/node/pull/8512
652    description: Custom dictionaries are now supported by `InflateRaw`.
653  - version: v5.0.0
654    pr-url: https://github.com/nodejs/node/pull/2595
655    description: A truncated input stream will now result in an `'error'` event.
656-->
657
658Decompress a raw deflate stream.
659
660## Class: `zlib.Unzip`
661
662<!-- YAML
663added: v0.5.8
664-->
665
666Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
667the header.
668
669## Class: `zlib.ZlibBase`
670
671<!-- YAML
672added: v0.5.8
673changes:
674  - version:
675     - v11.7.0
676     - v10.16.0
677    pr-url: https://github.com/nodejs/node/pull/24939
678    description: This class was renamed from `Zlib` to `ZlibBase`.
679-->
680
681Not exported by the `node:zlib` module. It is documented here because it is the
682base class of the compressor/decompressor classes.
683
684This class inherits from [`stream.Transform`][], allowing `node:zlib` objects to
685be used in pipes and similar stream operations.
686
687### `zlib.bytesRead`
688
689<!-- YAML
690added: v8.1.0
691deprecated: v10.0.0
692-->
693
694> Stability: 0 - Deprecated: Use [`zlib.bytesWritten`][] instead.
695
696* {number}
697
698Deprecated alias for [`zlib.bytesWritten`][]. This original name was chosen
699because it also made sense to interpret the value as the number of bytes
700read by the engine, but is inconsistent with other streams in Node.js that
701expose values under these names.
702
703### `zlib.bytesWritten`
704
705<!-- YAML
706added: v10.0.0
707-->
708
709* {number}
710
711The `zlib.bytesWritten` property specifies the number of bytes written to
712the engine, before the bytes are processed (compressed or decompressed,
713as appropriate for the derived class).
714
715### `zlib.close([callback])`
716
717<!-- YAML
718added: v0.9.4
719-->
720
721* `callback` {Function}
722
723Close the underlying handle.
724
725### `zlib.flush([kind, ]callback)`
726
727<!-- YAML
728added: v0.5.8
729-->
730
731* `kind` **Default:** `zlib.constants.Z_FULL_FLUSH` for zlib-based streams,
732  `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams.
733* `callback` {Function}
734
735Flush pending data. Don't call this frivolously, premature flushes negatively
736impact the effectiveness of the compression algorithm.
737
738Calling this only flushes data from the internal `zlib` state, and does not
739perform flushing of any kind on the streams level. Rather, it behaves like a
740normal call to `.write()`, i.e. it will be queued up behind other pending
741writes and will only produce output when data is being read from the stream.
742
743### `zlib.params(level, strategy, callback)`
744
745<!-- YAML
746added: v0.11.4
747-->
748
749* `level` {integer}
750* `strategy` {integer}
751* `callback` {Function}
752
753This function is only available for zlib-based streams, i.e. not Brotli.
754
755Dynamically update the compression level and compression strategy.
756Only applicable to deflate algorithm.
757
758### `zlib.reset()`
759
760<!-- YAML
761added: v0.7.0
762-->
763
764Reset the compressor/decompressor to factory defaults. Only applicable to
765the inflate and deflate algorithms.
766
767## `zlib.constants`
768
769<!-- YAML
770added: v7.0.0
771-->
772
773Provides an object enumerating Zlib-related constants.
774
775## `zlib.createBrotliCompress([options])`
776
777<!-- YAML
778added:
779 - v11.7.0
780 - v10.16.0
781-->
782
783* `options` {brotli options}
784
785Creates and returns a new [`BrotliCompress`][] object.
786
787## `zlib.createBrotliDecompress([options])`
788
789<!-- YAML
790added:
791 - v11.7.0
792 - v10.16.0
793-->
794
795* `options` {brotli options}
796
797Creates and returns a new [`BrotliDecompress`][] object.
798
799## `zlib.createDeflate([options])`
800
801<!-- YAML
802added: v0.5.8
803-->
804
805* `options` {zlib options}
806
807Creates and returns a new [`Deflate`][] object.
808
809## `zlib.createDeflateRaw([options])`
810
811<!-- YAML
812added: v0.5.8
813-->
814
815* `options` {zlib options}
816
817Creates and returns a new [`DeflateRaw`][] object.
818
819An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when `windowBits`
820is set to 8 for raw deflate streams. zlib would automatically set `windowBits`
821to 9 if was initially set to 8. Newer versions of zlib will throw an exception,
822so Node.js restored the original behavior of upgrading a value of 8 to 9,
823since passing `windowBits = 9` to zlib actually results in a compressed stream
824that effectively uses an 8-bit window only.
825
826## `zlib.createGunzip([options])`
827
828<!-- YAML
829added: v0.5.8
830-->
831
832* `options` {zlib options}
833
834Creates and returns a new [`Gunzip`][] object.
835
836## `zlib.createGzip([options])`
837
838<!-- YAML
839added: v0.5.8
840-->
841
842* `options` {zlib options}
843
844Creates and returns a new [`Gzip`][] object.
845See [example][zlib.createGzip example].
846
847## `zlib.createInflate([options])`
848
849<!-- YAML
850added: v0.5.8
851-->
852
853* `options` {zlib options}
854
855Creates and returns a new [`Inflate`][] object.
856
857## `zlib.createInflateRaw([options])`
858
859<!-- YAML
860added: v0.5.8
861-->
862
863* `options` {zlib options}
864
865Creates and returns a new [`InflateRaw`][] object.
866
867## `zlib.createUnzip([options])`
868
869<!-- YAML
870added: v0.5.8
871-->
872
873* `options` {zlib options}
874
875Creates and returns a new [`Unzip`][] object.
876
877## Convenience methods
878
879<!--type=misc-->
880
881All of these take a [`Buffer`][], [`TypedArray`][], [`DataView`][],
882[`ArrayBuffer`][] or string as the first argument, an optional second argument
883to supply options to the `zlib` classes and will call the supplied callback
884with `callback(error, result)`.
885
886Every method has a `*Sync` counterpart, which accept the same arguments, but
887without a callback.
888
889### `zlib.brotliCompress(buffer[, options], callback)`
890
891<!-- YAML
892added:
893 - v11.7.0
894 - v10.16.0
895-->
896
897* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
898* `options` {brotli options}
899* `callback` {Function}
900
901### `zlib.brotliCompressSync(buffer[, options])`
902
903<!-- YAML
904added:
905 - v11.7.0
906 - v10.16.0
907-->
908
909* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
910* `options` {brotli options}
911
912Compress a chunk of data with [`BrotliCompress`][].
913
914### `zlib.brotliDecompress(buffer[, options], callback)`
915
916<!-- YAML
917added:
918 - v11.7.0
919 - v10.16.0
920-->
921
922* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
923* `options` {brotli options}
924* `callback` {Function}
925
926### `zlib.brotliDecompressSync(buffer[, options])`
927
928<!-- YAML
929added:
930 - v11.7.0
931 - v10.16.0
932-->
933
934* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
935* `options` {brotli options}
936
937Decompress a chunk of data with [`BrotliDecompress`][].
938
939### `zlib.deflate(buffer[, options], callback)`
940
941<!-- YAML
942added: v0.6.0
943changes:
944  - version: v9.4.0
945    pr-url: https://github.com/nodejs/node/pull/16042
946    description: The `buffer` parameter can be an `ArrayBuffer`.
947  - version: v8.0.0
948    pr-url: https://github.com/nodejs/node/pull/12223
949    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
950  - version: v8.0.0
951    pr-url: https://github.com/nodejs/node/pull/12001
952    description: The `buffer` parameter can be an `Uint8Array` now.
953-->
954
955* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
956* `options` {zlib options}
957* `callback` {Function}
958
959### `zlib.deflateSync(buffer[, options])`
960
961<!-- YAML
962added: v0.11.12
963changes:
964  - version: v9.4.0
965    pr-url: https://github.com/nodejs/node/pull/16042
966    description: The `buffer` parameter can be an `ArrayBuffer`.
967  - version: v8.0.0
968    pr-url: https://github.com/nodejs/node/pull/12223
969    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
970  - version: v8.0.0
971    pr-url: https://github.com/nodejs/node/pull/12001
972    description: The `buffer` parameter can be an `Uint8Array` now.
973-->
974
975* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
976* `options` {zlib options}
977
978Compress a chunk of data with [`Deflate`][].
979
980### `zlib.deflateRaw(buffer[, options], callback)`
981
982<!-- YAML
983added: v0.6.0
984changes:
985  - version: v8.0.0
986    pr-url: https://github.com/nodejs/node/pull/12223
987    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
988  - version: v8.0.0
989    pr-url: https://github.com/nodejs/node/pull/12001
990    description: The `buffer` parameter can be an `Uint8Array` now.
991-->
992
993* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
994* `options` {zlib options}
995* `callback` {Function}
996
997### `zlib.deflateRawSync(buffer[, options])`
998
999<!-- YAML
1000added: v0.11.12
1001changes:
1002  - version: v9.4.0
1003    pr-url: https://github.com/nodejs/node/pull/16042
1004    description: The `buffer` parameter can be an `ArrayBuffer`.
1005  - version: v8.0.0
1006    pr-url: https://github.com/nodejs/node/pull/12223
1007    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1008  - version: v8.0.0
1009    pr-url: https://github.com/nodejs/node/pull/12001
1010    description: The `buffer` parameter can be an `Uint8Array` now.
1011-->
1012
1013* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1014* `options` {zlib options}
1015
1016Compress a chunk of data with [`DeflateRaw`][].
1017
1018### `zlib.gunzip(buffer[, options], callback)`
1019
1020<!-- YAML
1021added: v0.6.0
1022changes:
1023  - version: v9.4.0
1024    pr-url: https://github.com/nodejs/node/pull/16042
1025    description: The `buffer` parameter can be an `ArrayBuffer`.
1026  - version: v8.0.0
1027    pr-url: https://github.com/nodejs/node/pull/12223
1028    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1029  - version: v8.0.0
1030    pr-url: https://github.com/nodejs/node/pull/12001
1031    description: The `buffer` parameter can be an `Uint8Array` now.
1032-->
1033
1034* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1035* `options` {zlib options}
1036* `callback` {Function}
1037
1038### `zlib.gunzipSync(buffer[, options])`
1039
1040<!-- YAML
1041added: v0.11.12
1042changes:
1043  - version: v9.4.0
1044    pr-url: https://github.com/nodejs/node/pull/16042
1045    description: The `buffer` parameter can be an `ArrayBuffer`.
1046  - version: v8.0.0
1047    pr-url: https://github.com/nodejs/node/pull/12223
1048    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1049  - version: v8.0.0
1050    pr-url: https://github.com/nodejs/node/pull/12001
1051    description: The `buffer` parameter can be an `Uint8Array` now.
1052-->
1053
1054* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1055* `options` {zlib options}
1056
1057Decompress a chunk of data with [`Gunzip`][].
1058
1059### `zlib.gzip(buffer[, options], callback)`
1060
1061<!-- YAML
1062added: v0.6.0
1063changes:
1064  - version: v9.4.0
1065    pr-url: https://github.com/nodejs/node/pull/16042
1066    description: The `buffer` parameter can be an `ArrayBuffer`.
1067  - version: v8.0.0
1068    pr-url: https://github.com/nodejs/node/pull/12223
1069    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1070  - version: v8.0.0
1071    pr-url: https://github.com/nodejs/node/pull/12001
1072    description: The `buffer` parameter can be an `Uint8Array` now.
1073-->
1074
1075* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1076* `options` {zlib options}
1077* `callback` {Function}
1078
1079### `zlib.gzipSync(buffer[, options])`
1080
1081<!-- YAML
1082added: v0.11.12
1083changes:
1084  - version: v9.4.0
1085    pr-url: https://github.com/nodejs/node/pull/16042
1086    description: The `buffer` parameter can be an `ArrayBuffer`.
1087  - version: v8.0.0
1088    pr-url: https://github.com/nodejs/node/pull/12223
1089    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1090  - version: v8.0.0
1091    pr-url: https://github.com/nodejs/node/pull/12001
1092    description: The `buffer` parameter can be an `Uint8Array` now.
1093-->
1094
1095* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1096* `options` {zlib options}
1097
1098Compress a chunk of data with [`Gzip`][].
1099
1100### `zlib.inflate(buffer[, options], callback)`
1101
1102<!-- YAML
1103added: v0.6.0
1104changes:
1105  - version: v9.4.0
1106    pr-url: https://github.com/nodejs/node/pull/16042
1107    description: The `buffer` parameter can be an `ArrayBuffer`.
1108  - version: v8.0.0
1109    pr-url: https://github.com/nodejs/node/pull/12223
1110    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1111  - version: v8.0.0
1112    pr-url: https://github.com/nodejs/node/pull/12001
1113    description: The `buffer` parameter can be an `Uint8Array` now.
1114-->
1115
1116* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1117* `options` {zlib options}
1118* `callback` {Function}
1119
1120### `zlib.inflateSync(buffer[, options])`
1121
1122<!-- YAML
1123added: v0.11.12
1124changes:
1125  - version: v9.4.0
1126    pr-url: https://github.com/nodejs/node/pull/16042
1127    description: The `buffer` parameter can be an `ArrayBuffer`.
1128  - version: v8.0.0
1129    pr-url: https://github.com/nodejs/node/pull/12223
1130    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1131  - version: v8.0.0
1132    pr-url: https://github.com/nodejs/node/pull/12001
1133    description: The `buffer` parameter can be an `Uint8Array` now.
1134-->
1135
1136* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1137* `options` {zlib options}
1138
1139Decompress a chunk of data with [`Inflate`][].
1140
1141### `zlib.inflateRaw(buffer[, options], callback)`
1142
1143<!-- YAML
1144added: v0.6.0
1145changes:
1146  - version: v9.4.0
1147    pr-url: https://github.com/nodejs/node/pull/16042
1148    description: The `buffer` parameter can be an `ArrayBuffer`.
1149  - version: v8.0.0
1150    pr-url: https://github.com/nodejs/node/pull/12223
1151    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1152  - version: v8.0.0
1153    pr-url: https://github.com/nodejs/node/pull/12001
1154    description: The `buffer` parameter can be an `Uint8Array` now.
1155-->
1156
1157* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1158* `options` {zlib options}
1159* `callback` {Function}
1160
1161### `zlib.inflateRawSync(buffer[, options])`
1162
1163<!-- YAML
1164added: v0.11.12
1165changes:
1166  - version: v9.4.0
1167    pr-url: https://github.com/nodejs/node/pull/16042
1168    description: The `buffer` parameter can be an `ArrayBuffer`.
1169  - version: v8.0.0
1170    pr-url: https://github.com/nodejs/node/pull/12223
1171    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1172  - version: v8.0.0
1173    pr-url: https://github.com/nodejs/node/pull/12001
1174    description: The `buffer` parameter can be an `Uint8Array` now.
1175-->
1176
1177* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1178* `options` {zlib options}
1179
1180Decompress a chunk of data with [`InflateRaw`][].
1181
1182### `zlib.unzip(buffer[, options], callback)`
1183
1184<!-- YAML
1185added: v0.6.0
1186changes:
1187  - version: v9.4.0
1188    pr-url: https://github.com/nodejs/node/pull/16042
1189    description: The `buffer` parameter can be an `ArrayBuffer`.
1190  - version: v8.0.0
1191    pr-url: https://github.com/nodejs/node/pull/12223
1192    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1193  - version: v8.0.0
1194    pr-url: https://github.com/nodejs/node/pull/12001
1195    description: The `buffer` parameter can be an `Uint8Array` now.
1196-->
1197
1198* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1199* `options` {zlib options}
1200* `callback` {Function}
1201
1202### `zlib.unzipSync(buffer[, options])`
1203
1204<!-- YAML
1205added: v0.11.12
1206changes:
1207  - version: v9.4.0
1208    pr-url: https://github.com/nodejs/node/pull/16042
1209    description: The `buffer` parameter can be an `ArrayBuffer`.
1210  - version: v8.0.0
1211    pr-url: https://github.com/nodejs/node/pull/12223
1212    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1213  - version: v8.0.0
1214    pr-url: https://github.com/nodejs/node/pull/12001
1215    description: The `buffer` parameter can be an `Uint8Array` now.
1216-->
1217
1218* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1219* `options` {zlib options}
1220
1221Decompress a chunk of data with [`Unzip`][].
1222
1223[Brotli parameters]: #brotli-constants
1224[Memory usage tuning]: #memory-usage-tuning
1225[RFC 7932]: https://www.rfc-editor.org/rfc/rfc7932.txt
1226[Streams API]: stream.md
1227[`.flush()`]: #zlibflushkind-callback
1228[`Accept-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
1229[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
1230[`BrotliCompress`]: #class-zlibbrotlicompress
1231[`BrotliDecompress`]: #class-zlibbrotlidecompress
1232[`Buffer`]: buffer.md#class-buffer
1233[`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
1234[`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
1235[`DeflateRaw`]: #class-zlibdeflateraw
1236[`Deflate`]: #class-zlibdeflate
1237[`Gunzip`]: #class-zlibgunzip
1238[`Gzip`]: #class-zlibgzip
1239[`InflateRaw`]: #class-zlibinflateraw
1240[`Inflate`]: #class-zlibinflate
1241[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
1242[`Unzip`]: #class-zlibunzip
1243[`buffer.kMaxLength`]: buffer.md#bufferkmaxlength
1244[`deflateInit2` and `inflateInit2`]: https://zlib.net/manual.html#Advanced
1245[`stream.Transform`]: stream.md#class-streamtransform
1246[`zlib.bytesWritten`]: #zlibbyteswritten
1247[convenience methods]: #convenience-methods
1248[zlib documentation]: https://zlib.net/manual.html#Constants
1249[zlib.createGzip example]: #zlib
1250