• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Zlib
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/zlib.js -->
8
9The `zlib` module provides compression functionality implemented using Gzip,
10Deflate/Inflate, and Brotli.
11
12To access it:
13
14```js
15const zlib = require('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('zlib');
26const { pipeline } = require('stream');
27const {
28  createReadStream,
29  createWriteStream
30} = require('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('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('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('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('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 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 `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('zlib');
144const http = require('http');
145const fs = require('fs');
146const { pipeline } = require('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('zlib');
185const http = require('http');
186const fs = require('fs');
187const { pipeline } = require('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```js
269(1 << (windowBits + 2)) + (1 << (memLevel + 9))
270```
271
272That is: 128K for `windowBits` = 15 + 128K for `memLevel` = 8
273(default values) plus a few kilobytes for small objects.
274
275For example, to reduce the default memory requirements from 256K to 128K, the
276options should be set to:
277
278```js
279const options = { windowBits: 14, memLevel: 7 };
280```
281
282This will, however, generally degrade compression.
283
284The memory requirements for inflate are (in bytes) `1 << windowBits`.
285That is, 32K for `windowBits` = 15 (default value) plus a few kilobytes
286for small objects.
287
288This is in addition to a single internal output slab buffer of size
289`chunkSize`, which defaults to 16K.
290
291The speed of `zlib` compression is affected most dramatically by the
292`level` setting. A higher level will result in better compression, but
293will take longer to complete. A lower level will result in less
294compression, but will be much faster.
295
296In general, greater memory usage options will mean that Node.js has to make
297fewer calls to `zlib` because it will be able to process more data on
298each `write` operation. So, this is another factor that affects the
299speed, at the cost of memory usage.
300
301### For Brotli-based streams
302
303There are equivalents to the zlib options for Brotli-based streams, although
304these options have different ranges than the zlib ones:
305
306* zlib’s `level` option matches Brotli’s `BROTLI_PARAM_QUALITY` option.
307* zlib’s `windowBits` option matches Brotli’s `BROTLI_PARAM_LGWIN` option.
308
309See [below][Brotli parameters] for more details on Brotli-specific options.
310
311## Flushing
312
313Calling [`.flush()`][] on a compression stream will make `zlib` return as much
314output as currently possible. This may come at the cost of degraded compression
315quality, but can be useful when data needs to be available as soon as possible.
316
317In the following example, `flush()` is used to write a compressed partial
318HTTP response to the client:
319
320```js
321const zlib = require('zlib');
322const http = require('http');
323const { pipeline } = require('stream');
324
325http.createServer((request, response) => {
326  // For the sake of simplicity, the Accept-Encoding checks are omitted.
327  response.writeHead(200, { 'content-encoding': 'gzip' });
328  const output = zlib.createGzip();
329  let i;
330
331  pipeline(output, response, (err) => {
332    if (err) {
333      // If an error occurs, there's not much we can do because
334      // the server has already sent the 200 response code and
335      // some amount of data has already been sent to the client.
336      // The best we can do is terminate the response immediately
337      // and log the error.
338      clearInterval(i);
339      response.end();
340      console.error('An error occurred:', err);
341    }
342  });
343
344  i = setInterval(() => {
345    output.write(`The current time is ${Date()}\n`, () => {
346      // The data has been passed to zlib, but the compression algorithm may
347      // have decided to buffer the data for more efficient compression.
348      // Calling .flush() will make the data available as soon as the client
349      // is ready to receive it.
350      output.flush();
351    });
352  }, 1000);
353}).listen(1337);
354```
355
356## Constants
357<!-- YAML
358added: v0.5.8
359-->
360
361<!--type=misc-->
362
363### zlib constants
364
365All of the constants defined in `zlib.h` are also defined on
366`require('zlib').constants`. In the normal course of operations, it will not be
367necessary to use these constants. They are documented so that their presence is
368not surprising. This section is taken almost directly from the
369[zlib documentation][].
370
371Previously, the constants were available directly from `require('zlib')`, for
372instance `zlib.Z_NO_FLUSH`. Accessing the constants directly from the module is
373currently still possible but is deprecated.
374
375Allowed flush values.
376
377* `zlib.constants.Z_NO_FLUSH`
378* `zlib.constants.Z_PARTIAL_FLUSH`
379* `zlib.constants.Z_SYNC_FLUSH`
380* `zlib.constants.Z_FULL_FLUSH`
381* `zlib.constants.Z_FINISH`
382* `zlib.constants.Z_BLOCK`
383* `zlib.constants.Z_TREES`
384
385Return codes for the compression/decompression functions. Negative
386values are errors, positive values are used for special but normal
387events.
388
389* `zlib.constants.Z_OK`
390* `zlib.constants.Z_STREAM_END`
391* `zlib.constants.Z_NEED_DICT`
392* `zlib.constants.Z_ERRNO`
393* `zlib.constants.Z_STREAM_ERROR`
394* `zlib.constants.Z_DATA_ERROR`
395* `zlib.constants.Z_MEM_ERROR`
396* `zlib.constants.Z_BUF_ERROR`
397* `zlib.constants.Z_VERSION_ERROR`
398
399Compression levels.
400
401* `zlib.constants.Z_NO_COMPRESSION`
402* `zlib.constants.Z_BEST_SPEED`
403* `zlib.constants.Z_BEST_COMPRESSION`
404* `zlib.constants.Z_DEFAULT_COMPRESSION`
405
406Compression strategy.
407
408* `zlib.constants.Z_FILTERED`
409* `zlib.constants.Z_HUFFMAN_ONLY`
410* `zlib.constants.Z_RLE`
411* `zlib.constants.Z_FIXED`
412* `zlib.constants.Z_DEFAULT_STRATEGY`
413
414### Brotli constants
415<!-- YAML
416added: v11.7.0
417-->
418
419There are several options and other constants available for Brotli-based
420streams:
421
422#### Flush operations
423
424The following values are valid flush operations for Brotli-based streams:
425
426* `zlib.constants.BROTLI_OPERATION_PROCESS` (default for all operations)
427* `zlib.constants.BROTLI_OPERATION_FLUSH` (default when calling `.flush()`)
428* `zlib.constants.BROTLI_OPERATION_FINISH` (default for the last chunk)
429* `zlib.constants.BROTLI_OPERATION_EMIT_METADATA`
430  * This particular operation may be hard to use in a Node.js context,
431     as the streaming layer makes it hard to know which data will end up
432     in this frame. Also, there is currently no way to consume this data through
433     the Node.js API.
434
435#### Compressor options
436
437There are several options that can be set on Brotli encoders, affecting
438compression efficiency and speed. Both the keys and the values can be accessed
439as properties of the `zlib.constants` object.
440
441The most important options are:
442
443* `BROTLI_PARAM_MODE`
444  * `BROTLI_MODE_GENERIC` (default)
445  * `BROTLI_MODE_TEXT`, adjusted for UTF-8 text
446  * `BROTLI_MODE_FONT`, adjusted for WOFF 2.0 fonts
447* `BROTLI_PARAM_QUALITY`
448  * Ranges from `BROTLI_MIN_QUALITY` to `BROTLI_MAX_QUALITY`,
449    with a default of `BROTLI_DEFAULT_QUALITY`.
450* `BROTLI_PARAM_SIZE_HINT`
451  * Integer value representing the expected input size;
452    defaults to `0` for an unknown input size.
453
454The following flags can be set for advanced control over the compression
455algorithm and memory usage tuning:
456
457* `BROTLI_PARAM_LGWIN`
458  * Ranges from `BROTLI_MIN_WINDOW_BITS` to `BROTLI_MAX_WINDOW_BITS`,
459    with a default of `BROTLI_DEFAULT_WINDOW`, or up to
460    `BROTLI_LARGE_MAX_WINDOW_BITS` if the `BROTLI_PARAM_LARGE_WINDOW` flag
461    is set.
462* `BROTLI_PARAM_LGBLOCK`
463  * Ranges from `BROTLI_MIN_INPUT_BLOCK_BITS` to `BROTLI_MAX_INPUT_BLOCK_BITS`.
464* `BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING`
465  * Boolean flag that decreases compression ratio in favour of
466    decompression speed.
467* `BROTLI_PARAM_LARGE_WINDOW`
468  * Boolean flag enabling “Large Window Brotli” mode (not compatible with the
469    Brotli format as standardized in [RFC 7932][]).
470* `BROTLI_PARAM_NPOSTFIX`
471  * Ranges from `0` to `BROTLI_MAX_NPOSTFIX`.
472* `BROTLI_PARAM_NDIRECT`
473  * Ranges from `0` to `15 << NPOSTFIX` in steps of `1 << NPOSTFIX`.
474
475#### Decompressor options
476
477These advanced options are available for controlling decompression:
478
479* `BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION`
480  * Boolean flag that affects internal memory allocation patterns.
481* `BROTLI_DECODER_PARAM_LARGE_WINDOW`
482  * Boolean flag enabling “Large Window Brotli” mode (not compatible with the
483    Brotli format as standardized in [RFC 7932][]).
484
485## Class: `Options`
486<!-- YAML
487added: v0.11.1
488changes:
489  - version: v12.19.0
490    pr-url: https://github.com/nodejs/node/pull/33516
491    description: The `maxOutputLength` option is supported now.
492  - version: v9.4.0
493    pr-url: https://github.com/nodejs/node/pull/16042
494    description: The `dictionary` option can be an `ArrayBuffer`.
495  - version: v8.0.0
496    pr-url: https://github.com/nodejs/node/pull/12001
497    description: The `dictionary` option can be an `Uint8Array` now.
498  - version: v5.11.0
499    pr-url: https://github.com/nodejs/node/pull/6069
500    description: The `finishFlush` option is supported now.
501-->
502
503<!--type=misc-->
504
505Each zlib-based class takes an `options` object. No options are required.
506
507Some options are only relevant when compressing and are
508ignored by the decompression classes.
509
510* `flush` {integer} **Default:** `zlib.constants.Z_NO_FLUSH`
511* `finishFlush` {integer} **Default:** `zlib.constants.Z_FINISH`
512* `chunkSize` {integer} **Default:** `16 * 1024`
513* `windowBits` {integer}
514* `level` {integer} (compression only)
515* `memLevel` {integer} (compression only)
516* `strategy` {integer} (compression only)
517* `dictionary` {Buffer|TypedArray|DataView|ArrayBuffer} (deflate/inflate only,
518  empty dictionary by default)
519* `info` {boolean} (If `true`, returns an object with `buffer` and `engine`.)
520* `maxOutputLength` {integer} Limits output size when using
521  [convenience methods][]. **Default:** [`buffer.kMaxLength`][]
522
523See the [`deflateInit2` and `inflateInit2`][] documentation for more
524information.
525
526## Class: `BrotliOptions`
527<!-- YAML
528added: v11.7.0
529changes:
530  - version: v12.19.0
531    pr-url: https://github.com/nodejs/node/pull/33516
532    description: The `maxOutputLength` option is supported now.
533-->
534
535<!--type=misc-->
536
537Each Brotli-based class takes an `options` object. All options are optional.
538
539* `flush` {integer} **Default:** `zlib.constants.BROTLI_OPERATION_PROCESS`
540* `finishFlush` {integer} **Default:** `zlib.constants.BROTLI_OPERATION_FINISH`
541* `chunkSize` {integer} **Default:** `16 * 1024`
542* `params` {Object} Key-value object containing indexed [Brotli parameters][].
543* `maxOutputLength` {integer} Limits output size when using
544  [convenience methods][]. **Default:** [`buffer.kMaxLength`][]
545
546For example:
547
548```js
549const stream = zlib.createBrotliCompress({
550  chunkSize: 32 * 1024,
551  params: {
552    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
553    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,
554    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size
555  }
556});
557```
558
559## Class: `zlib.BrotliCompress`
560<!-- YAML
561added: v11.7.0
562-->
563
564Compress data using the Brotli algorithm.
565
566## Class: `zlib.BrotliDecompress`
567<!-- YAML
568added: v11.7.0
569-->
570
571Decompress data using the Brotli algorithm.
572
573## Class: `zlib.Deflate`
574<!-- YAML
575added: v0.5.8
576-->
577
578Compress data using deflate.
579
580## Class: `zlib.DeflateRaw`
581<!-- YAML
582added: v0.5.8
583-->
584
585Compress data using deflate, and do not append a `zlib` header.
586
587## Class: `zlib.Gunzip`
588<!-- YAML
589added: v0.5.8
590changes:
591  - version: v6.0.0
592    pr-url: https://github.com/nodejs/node/pull/5883
593    description: Trailing garbage at the end of the input stream will now
594                 result in an `'error'` event.
595  - version: v5.9.0
596    pr-url: https://github.com/nodejs/node/pull/5120
597    description: Multiple concatenated gzip file members are supported now.
598  - version: v5.0.0
599    pr-url: https://github.com/nodejs/node/pull/2595
600    description: A truncated input stream will now result in an `'error'` event.
601-->
602
603Decompress a gzip stream.
604
605## Class: `zlib.Gzip`
606<!-- YAML
607added: v0.5.8
608-->
609
610Compress data using gzip.
611
612## Class: `zlib.Inflate`
613<!-- YAML
614added: v0.5.8
615changes:
616  - version: v5.0.0
617    pr-url: https://github.com/nodejs/node/pull/2595
618    description: A truncated input stream will now result in an `'error'` event.
619-->
620
621Decompress a deflate stream.
622
623## Class: `zlib.InflateRaw`
624<!-- YAML
625added: v0.5.8
626changes:
627  - version: v6.8.0
628    pr-url: https://github.com/nodejs/node/pull/8512
629    description: Custom dictionaries are now supported by `InflateRaw`.
630  - version: v5.0.0
631    pr-url: https://github.com/nodejs/node/pull/2595
632    description: A truncated input stream will now result in an `'error'` event.
633-->
634
635Decompress a raw deflate stream.
636
637## Class: `zlib.Unzip`
638<!-- YAML
639added: v0.5.8
640-->
641
642Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
643the header.
644
645## Class: `zlib.ZlibBase`
646<!-- YAML
647added: v0.5.8
648changes:
649  - version: v11.7.0
650    pr-url: https://github.com/nodejs/node/pull/24939
651    description: This class was renamed from `Zlib` to `ZlibBase`.
652-->
653
654Not exported by the `zlib` module. It is documented here because it is the base
655class of the compressor/decompressor classes.
656
657This class inherits from [`stream.Transform`][], allowing `zlib` objects to be
658used in pipes and similar stream operations.
659
660### `zlib.bytesRead`
661<!-- YAML
662added: v8.1.0
663deprecated: v10.0.0
664-->
665
666> Stability: 0 - Deprecated: Use [`zlib.bytesWritten`][] instead.
667
668* {number}
669
670Deprecated alias for [`zlib.bytesWritten`][]. This original name was chosen
671because it also made sense to interpret the value as the number of bytes
672read by the engine, but is inconsistent with other streams in Node.js that
673expose values under these names.
674
675### `zlib.bytesWritten`
676<!-- YAML
677added: v10.0.0
678-->
679
680* {number}
681
682The `zlib.bytesWritten` property specifies the number of bytes written to
683the engine, before the bytes are processed (compressed or decompressed,
684as appropriate for the derived class).
685
686### `zlib.close([callback])`
687<!-- YAML
688added: v0.9.4
689-->
690
691* `callback` {Function}
692
693Close the underlying handle.
694
695### `zlib.flush([kind, ]callback)`
696<!-- YAML
697added: v0.5.8
698-->
699
700* `kind` **Default:** `zlib.constants.Z_FULL_FLUSH` for zlib-based streams,
701  `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams.
702* `callback` {Function}
703
704Flush pending data. Don't call this frivolously, premature flushes negatively
705impact the effectiveness of the compression algorithm.
706
707Calling this only flushes data from the internal `zlib` state, and does not
708perform flushing of any kind on the streams level. Rather, it behaves like a
709normal call to `.write()`, i.e. it will be queued up behind other pending
710writes and will only produce output when data is being read from the stream.
711
712### `zlib.params(level, strategy, callback)`
713<!-- YAML
714added: v0.11.4
715-->
716
717* `level` {integer}
718* `strategy` {integer}
719* `callback` {Function}
720
721This function is only available for zlib-based streams, i.e. not Brotli.
722
723Dynamically update the compression level and compression strategy.
724Only applicable to deflate algorithm.
725
726### `zlib.reset()`
727<!-- YAML
728added: v0.7.0
729-->
730
731Reset the compressor/decompressor to factory defaults. Only applicable to
732the inflate and deflate algorithms.
733
734## `zlib.constants`
735<!-- YAML
736added: v7.0.0
737-->
738
739Provides an object enumerating Zlib-related constants.
740
741## `zlib.createBrotliCompress([options])`
742<!-- YAML
743added: v11.7.0
744-->
745
746* `options` {brotli options}
747
748Creates and returns a new [`BrotliCompress`][] object.
749
750## `zlib.createBrotliDecompress([options])`
751<!-- YAML
752added: v11.7.0
753-->
754
755* `options` {brotli options}
756
757Creates and returns a new [`BrotliDecompress`][] object.
758
759## `zlib.createDeflate([options])`
760<!-- YAML
761added: v0.5.8
762-->
763
764* `options` {zlib options}
765
766Creates and returns a new [`Deflate`][] object.
767
768## `zlib.createDeflateRaw([options])`
769<!-- YAML
770added: v0.5.8
771-->
772
773* `options` {zlib options}
774
775Creates and returns a new [`DeflateRaw`][] object.
776
777An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when `windowBits`
778is set to 8 for raw deflate streams. zlib would automatically set `windowBits`
779to 9 if was initially set to 8. Newer versions of zlib will throw an exception,
780so Node.js restored the original behavior of upgrading a value of 8 to 9,
781since passing `windowBits = 9` to zlib actually results in a compressed stream
782that effectively uses an 8-bit window only.
783
784## `zlib.createGunzip([options])`
785<!-- YAML
786added: v0.5.8
787-->
788
789* `options` {zlib options}
790
791Creates and returns a new [`Gunzip`][] object.
792
793## `zlib.createGzip([options])`
794<!-- YAML
795added: v0.5.8
796-->
797
798* `options` {zlib options}
799
800Creates and returns a new [`Gzip`][] object.
801See [example][zlib.createGzip example].
802
803## `zlib.createInflate([options])`
804<!-- YAML
805added: v0.5.8
806-->
807
808* `options` {zlib options}
809
810Creates and returns a new [`Inflate`][] object.
811
812## `zlib.createInflateRaw([options])`
813<!-- YAML
814added: v0.5.8
815-->
816
817* `options` {zlib options}
818
819Creates and returns a new [`InflateRaw`][] object.
820
821## `zlib.createUnzip([options])`
822<!-- YAML
823added: v0.5.8
824-->
825
826* `options` {zlib options}
827
828Creates and returns a new [`Unzip`][] object.
829
830## Convenience methods
831
832<!--type=misc-->
833
834All of these take a [`Buffer`][], [`TypedArray`][], [`DataView`][],
835[`ArrayBuffer`][] or string as the first argument, an optional second argument
836to supply options to the `zlib` classes and will call the supplied callback
837with `callback(error, result)`.
838
839Every method has a `*Sync` counterpart, which accept the same arguments, but
840without a callback.
841
842### `zlib.brotliCompress(buffer[, options], callback)`
843<!-- YAML
844added: v11.7.0
845-->
846
847* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
848* `options` {brotli options}
849* `callback` {Function}
850
851### `zlib.brotliCompressSync(buffer[, options])`
852<!-- YAML
853added: v11.7.0
854-->
855
856* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
857* `options` {brotli options}
858
859Compress a chunk of data with [`BrotliCompress`][].
860
861### `zlib.brotliDecompress(buffer[, options], callback)`
862<!-- YAML
863added: v11.7.0
864-->
865
866* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
867* `options` {brotli options}
868* `callback` {Function}
869
870### `zlib.brotliDecompressSync(buffer[, options])`
871<!-- YAML
872added: v11.7.0
873-->
874
875* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
876* `options` {brotli options}
877
878Decompress a chunk of data with [`BrotliDecompress`][].
879
880### `zlib.deflate(buffer[, options], callback)`
881<!-- YAML
882added: v0.6.0
883changes:
884  - version: v9.4.0
885    pr-url: https://github.com/nodejs/node/pull/16042
886    description: The `buffer` parameter can be an `ArrayBuffer`.
887  - version: v8.0.0
888    pr-url: https://github.com/nodejs/node/pull/12223
889    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
890  - version: v8.0.0
891    pr-url: https://github.com/nodejs/node/pull/12001
892    description: The `buffer` parameter can be an `Uint8Array` now.
893-->
894
895* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
896* `options` {zlib options}
897* `callback` {Function}
898
899### `zlib.deflateSync(buffer[, options])`
900<!-- YAML
901added: v0.11.12
902changes:
903  - version: v9.4.0
904    pr-url: https://github.com/nodejs/node/pull/16042
905    description: The `buffer` parameter can be an `ArrayBuffer`.
906  - version: v8.0.0
907    pr-url: https://github.com/nodejs/node/pull/12223
908    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
909  - version: v8.0.0
910    pr-url: https://github.com/nodejs/node/pull/12001
911    description: The `buffer` parameter can be an `Uint8Array` now.
912-->
913
914* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
915* `options` {zlib options}
916
917Compress a chunk of data with [`Deflate`][].
918
919### `zlib.deflateRaw(buffer[, options], callback)`
920<!-- YAML
921added: v0.6.0
922changes:
923  - version: v8.0.0
924    pr-url: https://github.com/nodejs/node/pull/12223
925    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
926  - version: v8.0.0
927    pr-url: https://github.com/nodejs/node/pull/12001
928    description: The `buffer` parameter can be an `Uint8Array` now.
929-->
930
931* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
932* `options` {zlib options}
933* `callback` {Function}
934
935### `zlib.deflateRawSync(buffer[, options])`
936<!-- YAML
937added: v0.11.12
938changes:
939  - version: v9.4.0
940    pr-url: https://github.com/nodejs/node/pull/16042
941    description: The `buffer` parameter can be an `ArrayBuffer`.
942  - version: v8.0.0
943    pr-url: https://github.com/nodejs/node/pull/12223
944    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
945  - version: v8.0.0
946    pr-url: https://github.com/nodejs/node/pull/12001
947    description: The `buffer` parameter can be an `Uint8Array` now.
948-->
949
950* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
951* `options` {zlib options}
952
953Compress a chunk of data with [`DeflateRaw`][].
954
955### `zlib.gunzip(buffer[, options], callback)`
956<!-- YAML
957added: v0.6.0
958changes:
959  - version: v9.4.0
960    pr-url: https://github.com/nodejs/node/pull/16042
961    description: The `buffer` parameter can be an `ArrayBuffer`.
962  - version: v8.0.0
963    pr-url: https://github.com/nodejs/node/pull/12223
964    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
965  - version: v8.0.0
966    pr-url: https://github.com/nodejs/node/pull/12001
967    description: The `buffer` parameter can be an `Uint8Array` now.
968-->
969
970* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
971* `options` {zlib options}
972* `callback` {Function}
973
974### `zlib.gunzipSync(buffer[, options])`
975<!-- YAML
976added: v0.11.12
977changes:
978  - version: v9.4.0
979    pr-url: https://github.com/nodejs/node/pull/16042
980    description: The `buffer` parameter can be an `ArrayBuffer`.
981  - version: v8.0.0
982    pr-url: https://github.com/nodejs/node/pull/12223
983    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
984  - version: v8.0.0
985    pr-url: https://github.com/nodejs/node/pull/12001
986    description: The `buffer` parameter can be an `Uint8Array` now.
987-->
988
989* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
990* `options` {zlib options}
991
992Decompress a chunk of data with [`Gunzip`][].
993
994### `zlib.gzip(buffer[, options], callback)`
995<!-- YAML
996added: v0.6.0
997changes:
998  - version: v9.4.0
999    pr-url: https://github.com/nodejs/node/pull/16042
1000    description: The `buffer` parameter can be an `ArrayBuffer`.
1001  - version: v8.0.0
1002    pr-url: https://github.com/nodejs/node/pull/12223
1003    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1004  - version: v8.0.0
1005    pr-url: https://github.com/nodejs/node/pull/12001
1006    description: The `buffer` parameter can be an `Uint8Array` now.
1007-->
1008
1009* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1010* `options` {zlib options}
1011* `callback` {Function}
1012
1013### `zlib.gzipSync(buffer[, options])`
1014<!-- YAML
1015added: v0.11.12
1016changes:
1017  - version: v9.4.0
1018    pr-url: https://github.com/nodejs/node/pull/16042
1019    description: The `buffer` parameter can be an `ArrayBuffer`.
1020  - version: v8.0.0
1021    pr-url: https://github.com/nodejs/node/pull/12223
1022    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1023  - version: v8.0.0
1024    pr-url: https://github.com/nodejs/node/pull/12001
1025    description: The `buffer` parameter can be an `Uint8Array` now.
1026-->
1027
1028* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1029* `options` {zlib options}
1030
1031Compress a chunk of data with [`Gzip`][].
1032
1033### `zlib.inflate(buffer[, options], callback)`
1034<!-- YAML
1035added: v0.6.0
1036changes:
1037  - version: v9.4.0
1038    pr-url: https://github.com/nodejs/node/pull/16042
1039    description: The `buffer` parameter can be an `ArrayBuffer`.
1040  - version: v8.0.0
1041    pr-url: https://github.com/nodejs/node/pull/12223
1042    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1043  - version: v8.0.0
1044    pr-url: https://github.com/nodejs/node/pull/12001
1045    description: The `buffer` parameter can be an `Uint8Array` now.
1046-->
1047
1048* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1049* `options` {zlib options}
1050* `callback` {Function}
1051
1052### `zlib.inflateSync(buffer[, options])`
1053<!-- YAML
1054added: v0.11.12
1055changes:
1056  - version: v9.4.0
1057    pr-url: https://github.com/nodejs/node/pull/16042
1058    description: The `buffer` parameter can be an `ArrayBuffer`.
1059  - version: v8.0.0
1060    pr-url: https://github.com/nodejs/node/pull/12223
1061    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1062  - version: v8.0.0
1063    pr-url: https://github.com/nodejs/node/pull/12001
1064    description: The `buffer` parameter can be an `Uint8Array` now.
1065-->
1066
1067* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1068* `options` {zlib options}
1069
1070Decompress a chunk of data with [`Inflate`][].
1071
1072### `zlib.inflateRaw(buffer[, options], callback)`
1073<!-- YAML
1074added: v0.6.0
1075changes:
1076  - version: v9.4.0
1077    pr-url: https://github.com/nodejs/node/pull/16042
1078    description: The `buffer` parameter can be an `ArrayBuffer`.
1079  - version: v8.0.0
1080    pr-url: https://github.com/nodejs/node/pull/12223
1081    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1082  - version: v8.0.0
1083    pr-url: https://github.com/nodejs/node/pull/12001
1084    description: The `buffer` parameter can be an `Uint8Array` now.
1085-->
1086
1087* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1088* `options` {zlib options}
1089* `callback` {Function}
1090
1091### `zlib.inflateRawSync(buffer[, options])`
1092<!-- YAML
1093added: v0.11.12
1094changes:
1095  - version: v9.4.0
1096    pr-url: https://github.com/nodejs/node/pull/16042
1097    description: The `buffer` parameter can be an `ArrayBuffer`.
1098  - version: v8.0.0
1099    pr-url: https://github.com/nodejs/node/pull/12223
1100    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1101  - version: v8.0.0
1102    pr-url: https://github.com/nodejs/node/pull/12001
1103    description: The `buffer` parameter can be an `Uint8Array` now.
1104-->
1105
1106* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1107* `options` {zlib options}
1108
1109Decompress a chunk of data with [`InflateRaw`][].
1110
1111### `zlib.unzip(buffer[, options], callback)`
1112<!-- YAML
1113added: v0.6.0
1114changes:
1115  - version: v9.4.0
1116    pr-url: https://github.com/nodejs/node/pull/16042
1117    description: The `buffer` parameter can be an `ArrayBuffer`.
1118  - version: v8.0.0
1119    pr-url: https://github.com/nodejs/node/pull/12223
1120    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1121  - version: v8.0.0
1122    pr-url: https://github.com/nodejs/node/pull/12001
1123    description: The `buffer` parameter can be an `Uint8Array` now.
1124-->
1125
1126* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1127* `options` {zlib options}
1128* `callback` {Function}
1129
1130### `zlib.unzipSync(buffer[, options])`
1131<!-- YAML
1132added: v0.11.12
1133changes:
1134  - version: v9.4.0
1135    pr-url: https://github.com/nodejs/node/pull/16042
1136    description: The `buffer` parameter can be an `ArrayBuffer`.
1137  - version: v8.0.0
1138    pr-url: https://github.com/nodejs/node/pull/12223
1139    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1140  - version: v8.0.0
1141    pr-url: https://github.com/nodejs/node/pull/12001
1142    description: The `buffer` parameter can be an `Uint8Array` now.
1143-->
1144
1145* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1146* `options` {zlib options}
1147
1148Decompress a chunk of data with [`Unzip`][].
1149
1150[`.flush()`]: #zlib_zlib_flush_kind_callback
1151[`Accept-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
1152[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
1153[`BrotliCompress`]: #zlib_class_zlib_brotlicompress
1154[`BrotliDecompress`]: #zlib_class_zlib_brotlidecompress
1155[`Buffer`]: buffer.html#buffer_class_buffer
1156[`buffer.kMaxLength`]: buffer.html#buffer_buffer_kmaxlength
1157[`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
1158[`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
1159[`DeflateRaw`]: #zlib_class_zlib_deflateraw
1160[`Deflate`]: #zlib_class_zlib_deflate
1161[`Gunzip`]: #zlib_class_zlib_gunzip
1162[`Gzip`]: #zlib_class_zlib_gzip
1163[`InflateRaw`]: #zlib_class_zlib_inflateraw
1164[`Inflate`]: #zlib_class_zlib_inflate
1165[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
1166[`Unzip`]: #zlib_class_zlib_unzip
1167[`deflateInit2` and `inflateInit2`]: https://zlib.net/manual.html#Advanced
1168[`stream.Transform`]: stream.html#stream_class_stream_transform
1169[`zlib.bytesWritten`]: #zlib_zlib_byteswritten
1170[Brotli parameters]: #zlib_brotli_constants
1171[Memory usage tuning]: #zlib_memory_usage_tuning
1172[RFC 7932]: https://www.rfc-editor.org/rfc/rfc7932.txt
1173[Streams API]: stream.md
1174[convenience methods]: #zlib_convenience_methods
1175[zlib documentation]: https://zlib.net/manual.html#Constants
1176[zlib.createGzip example]: #zlib_zlib
1177