• 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:
417 - v11.7.0
418 - v10.16.0
419-->
420
421There are several options and other constants available for Brotli-based
422streams:
423
424#### Flush operations
425
426The following values are valid flush operations for Brotli-based streams:
427
428* `zlib.constants.BROTLI_OPERATION_PROCESS` (default for all operations)
429* `zlib.constants.BROTLI_OPERATION_FLUSH` (default when calling `.flush()`)
430* `zlib.constants.BROTLI_OPERATION_FINISH` (default for the last chunk)
431* `zlib.constants.BROTLI_OPERATION_EMIT_METADATA`
432  * This particular operation may be hard to use in a Node.js context,
433     as the streaming layer makes it hard to know which data will end up
434     in this frame. Also, there is currently no way to consume this data through
435     the Node.js API.
436
437#### Compressor options
438
439There are several options that can be set on Brotli encoders, affecting
440compression efficiency and speed. Both the keys and the values can be accessed
441as properties of the `zlib.constants` object.
442
443The most important options are:
444
445* `BROTLI_PARAM_MODE`
446  * `BROTLI_MODE_GENERIC` (default)
447  * `BROTLI_MODE_TEXT`, adjusted for UTF-8 text
448  * `BROTLI_MODE_FONT`, adjusted for WOFF 2.0 fonts
449* `BROTLI_PARAM_QUALITY`
450  * Ranges from `BROTLI_MIN_QUALITY` to `BROTLI_MAX_QUALITY`,
451    with a default of `BROTLI_DEFAULT_QUALITY`.
452* `BROTLI_PARAM_SIZE_HINT`
453  * Integer value representing the expected input size;
454    defaults to `0` for an unknown input size.
455
456The following flags can be set for advanced control over the compression
457algorithm and memory usage tuning:
458
459* `BROTLI_PARAM_LGWIN`
460  * Ranges from `BROTLI_MIN_WINDOW_BITS` to `BROTLI_MAX_WINDOW_BITS`,
461    with a default of `BROTLI_DEFAULT_WINDOW`, or up to
462    `BROTLI_LARGE_MAX_WINDOW_BITS` if the `BROTLI_PARAM_LARGE_WINDOW` flag
463    is set.
464* `BROTLI_PARAM_LGBLOCK`
465  * Ranges from `BROTLI_MIN_INPUT_BLOCK_BITS` to `BROTLI_MAX_INPUT_BLOCK_BITS`.
466* `BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING`
467  * Boolean flag that decreases compression ratio in favour of
468    decompression speed.
469* `BROTLI_PARAM_LARGE_WINDOW`
470  * Boolean flag enabling “Large Window Brotli” mode (not compatible with the
471    Brotli format as standardized in [RFC 7932][]).
472* `BROTLI_PARAM_NPOSTFIX`
473  * Ranges from `0` to `BROTLI_MAX_NPOSTFIX`.
474* `BROTLI_PARAM_NDIRECT`
475  * Ranges from `0` to `15 << NPOSTFIX` in steps of `1 << NPOSTFIX`.
476
477#### Decompressor options
478
479These advanced options are available for controlling decompression:
480
481* `BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION`
482  * Boolean flag that affects internal memory allocation patterns.
483* `BROTLI_DECODER_PARAM_LARGE_WINDOW`
484  * Boolean flag enabling “Large Window Brotli” mode (not compatible with the
485    Brotli format as standardized in [RFC 7932][]).
486
487## Class: `Options`
488<!-- YAML
489added: v0.11.1
490changes:
491  - version:
492    - v14.5.0
493    - v12.19.0
494    pr-url: https://github.com/nodejs/node/pull/33516
495    description: The `maxOutputLength` option is supported now.
496  - version: v9.4.0
497    pr-url: https://github.com/nodejs/node/pull/16042
498    description: The `dictionary` option can be an `ArrayBuffer`.
499  - version: v8.0.0
500    pr-url: https://github.com/nodejs/node/pull/12001
501    description: The `dictionary` option can be an `Uint8Array` now.
502  - version: v5.11.0
503    pr-url: https://github.com/nodejs/node/pull/6069
504    description: The `finishFlush` option is supported now.
505-->
506
507<!--type=misc-->
508
509Each zlib-based class takes an `options` object. No options are required.
510
511Some options are only relevant when compressing and are
512ignored by the decompression classes.
513
514* `flush` {integer} **Default:** `zlib.constants.Z_NO_FLUSH`
515* `finishFlush` {integer} **Default:** `zlib.constants.Z_FINISH`
516* `chunkSize` {integer} **Default:** `16 * 1024`
517* `windowBits` {integer}
518* `level` {integer} (compression only)
519* `memLevel` {integer} (compression only)
520* `strategy` {integer} (compression only)
521* `dictionary` {Buffer|TypedArray|DataView|ArrayBuffer} (deflate/inflate only,
522  empty dictionary by default)
523* `info` {boolean} (If `true`, returns an object with `buffer` and `engine`.)
524* `maxOutputLength` {integer} Limits output size when using
525  [convenience methods][]. **Default:** [`buffer.kMaxLength`][]
526
527See the [`deflateInit2` and `inflateInit2`][] documentation for more
528information.
529
530## Class: `BrotliOptions`
531<!-- YAML
532added: v11.7.0
533changes:
534  - version: v14.5.0
535    pr-url: https://github.com/nodejs/node/pull/33516
536    description: The `maxOutputLength` option is supported now.
537-->
538
539<!--type=misc-->
540
541Each Brotli-based class takes an `options` object. All options are optional.
542
543* `flush` {integer} **Default:** `zlib.constants.BROTLI_OPERATION_PROCESS`
544* `finishFlush` {integer} **Default:** `zlib.constants.BROTLI_OPERATION_FINISH`
545* `chunkSize` {integer} **Default:** `16 * 1024`
546* `params` {Object} Key-value object containing indexed [Brotli parameters][].
547* `maxOutputLength` {integer} Limits output size when using
548  [convenience methods][]. **Default:** [`buffer.kMaxLength`][]
549
550For example:
551
552```js
553const stream = zlib.createBrotliCompress({
554  chunkSize: 32 * 1024,
555  params: {
556    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
557    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,
558    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size
559  }
560});
561```
562
563## Class: `zlib.BrotliCompress`
564<!-- YAML
565added:
566 - v11.7.0
567 - v10.16.0
568-->
569
570Compress data using the Brotli algorithm.
571
572## Class: `zlib.BrotliDecompress`
573<!-- YAML
574added:
575 - v11.7.0
576 - v10.16.0
577-->
578
579Decompress data using the Brotli algorithm.
580
581## Class: `zlib.Deflate`
582<!-- YAML
583added: v0.5.8
584-->
585
586Compress data using deflate.
587
588## Class: `zlib.DeflateRaw`
589<!-- YAML
590added: v0.5.8
591-->
592
593Compress data using deflate, and do not append a `zlib` header.
594
595## Class: `zlib.Gunzip`
596<!-- YAML
597added: v0.5.8
598changes:
599  - version: v6.0.0
600    pr-url: https://github.com/nodejs/node/pull/5883
601    description: Trailing garbage at the end of the input stream will now
602                 result in an `'error'` event.
603  - version: v5.9.0
604    pr-url: https://github.com/nodejs/node/pull/5120
605    description: Multiple concatenated gzip file members are supported now.
606  - version: v5.0.0
607    pr-url: https://github.com/nodejs/node/pull/2595
608    description: A truncated input stream will now result in an `'error'` event.
609-->
610
611Decompress a gzip stream.
612
613## Class: `zlib.Gzip`
614<!-- YAML
615added: v0.5.8
616-->
617
618Compress data using gzip.
619
620## Class: `zlib.Inflate`
621<!-- YAML
622added: v0.5.8
623changes:
624  - version: v5.0.0
625    pr-url: https://github.com/nodejs/node/pull/2595
626    description: A truncated input stream will now result in an `'error'` event.
627-->
628
629Decompress a deflate stream.
630
631## Class: `zlib.InflateRaw`
632<!-- YAML
633added: v0.5.8
634changes:
635  - version: v6.8.0
636    pr-url: https://github.com/nodejs/node/pull/8512
637    description: Custom dictionaries are now supported by `InflateRaw`.
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 raw deflate stream.
644
645## Class: `zlib.Unzip`
646<!-- YAML
647added: v0.5.8
648-->
649
650Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
651the header.
652
653## Class: `zlib.ZlibBase`
654<!-- YAML
655added: v0.5.8
656changes:
657  - version:
658     - v11.7.0
659     - v10.16.0
660    pr-url: https://github.com/nodejs/node/pull/24939
661    description: This class was renamed from `Zlib` to `ZlibBase`.
662-->
663
664Not exported by the `zlib` module. It is documented here because it is the base
665class of the compressor/decompressor classes.
666
667This class inherits from [`stream.Transform`][], allowing `zlib` objects to be
668used in pipes and similar stream operations.
669
670### `zlib.bytesRead`
671<!-- YAML
672added: v8.1.0
673deprecated: v10.0.0
674-->
675
676> Stability: 0 - Deprecated: Use [`zlib.bytesWritten`][] instead.
677
678* {number}
679
680Deprecated alias for [`zlib.bytesWritten`][]. This original name was chosen
681because it also made sense to interpret the value as the number of bytes
682read by the engine, but is inconsistent with other streams in Node.js that
683expose values under these names.
684
685### `zlib.bytesWritten`
686<!-- YAML
687added: v10.0.0
688-->
689
690* {number}
691
692The `zlib.bytesWritten` property specifies the number of bytes written to
693the engine, before the bytes are processed (compressed or decompressed,
694as appropriate for the derived class).
695
696### `zlib.close([callback])`
697<!-- YAML
698added: v0.9.4
699-->
700
701* `callback` {Function}
702
703Close the underlying handle.
704
705### `zlib.flush([kind, ]callback)`
706<!-- YAML
707added: v0.5.8
708-->
709
710* `kind` **Default:** `zlib.constants.Z_FULL_FLUSH` for zlib-based streams,
711  `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams.
712* `callback` {Function}
713
714Flush pending data. Don't call this frivolously, premature flushes negatively
715impact the effectiveness of the compression algorithm.
716
717Calling this only flushes data from the internal `zlib` state, and does not
718perform flushing of any kind on the streams level. Rather, it behaves like a
719normal call to `.write()`, i.e. it will be queued up behind other pending
720writes and will only produce output when data is being read from the stream.
721
722### `zlib.params(level, strategy, callback)`
723<!-- YAML
724added: v0.11.4
725-->
726
727* `level` {integer}
728* `strategy` {integer}
729* `callback` {Function}
730
731This function is only available for zlib-based streams, i.e. not Brotli.
732
733Dynamically update the compression level and compression strategy.
734Only applicable to deflate algorithm.
735
736### `zlib.reset()`
737<!-- YAML
738added: v0.7.0
739-->
740
741Reset the compressor/decompressor to factory defaults. Only applicable to
742the inflate and deflate algorithms.
743
744## `zlib.constants`
745<!-- YAML
746added: v7.0.0
747-->
748
749Provides an object enumerating Zlib-related constants.
750
751## `zlib.createBrotliCompress([options])`
752<!-- YAML
753added:
754 - v11.7.0
755 - v10.16.0
756-->
757
758* `options` {brotli options}
759
760Creates and returns a new [`BrotliCompress`][] object.
761
762## `zlib.createBrotliDecompress([options])`
763<!-- YAML
764added:
765 - v11.7.0
766 - v10.16.0
767-->
768
769* `options` {brotli options}
770
771Creates and returns a new [`BrotliDecompress`][] object.
772
773## `zlib.createDeflate([options])`
774<!-- YAML
775added: v0.5.8
776-->
777
778* `options` {zlib options}
779
780Creates and returns a new [`Deflate`][] object.
781
782## `zlib.createDeflateRaw([options])`
783<!-- YAML
784added: v0.5.8
785-->
786
787* `options` {zlib options}
788
789Creates and returns a new [`DeflateRaw`][] object.
790
791An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when `windowBits`
792is set to 8 for raw deflate streams. zlib would automatically set `windowBits`
793to 9 if was initially set to 8. Newer versions of zlib will throw an exception,
794so Node.js restored the original behavior of upgrading a value of 8 to 9,
795since passing `windowBits = 9` to zlib actually results in a compressed stream
796that effectively uses an 8-bit window only.
797
798## `zlib.createGunzip([options])`
799<!-- YAML
800added: v0.5.8
801-->
802
803* `options` {zlib options}
804
805Creates and returns a new [`Gunzip`][] object.
806
807## `zlib.createGzip([options])`
808<!-- YAML
809added: v0.5.8
810-->
811
812* `options` {zlib options}
813
814Creates and returns a new [`Gzip`][] object.
815See [example][zlib.createGzip example].
816
817## `zlib.createInflate([options])`
818<!-- YAML
819added: v0.5.8
820-->
821
822* `options` {zlib options}
823
824Creates and returns a new [`Inflate`][] object.
825
826## `zlib.createInflateRaw([options])`
827<!-- YAML
828added: v0.5.8
829-->
830
831* `options` {zlib options}
832
833Creates and returns a new [`InflateRaw`][] object.
834
835## `zlib.createUnzip([options])`
836<!-- YAML
837added: v0.5.8
838-->
839
840* `options` {zlib options}
841
842Creates and returns a new [`Unzip`][] object.
843
844## Convenience methods
845
846<!--type=misc-->
847
848All of these take a [`Buffer`][], [`TypedArray`][], [`DataView`][],
849[`ArrayBuffer`][] or string as the first argument, an optional second argument
850to supply options to the `zlib` classes and will call the supplied callback
851with `callback(error, result)`.
852
853Every method has a `*Sync` counterpart, which accept the same arguments, but
854without a callback.
855
856### `zlib.brotliCompress(buffer[, options], callback)`
857<!-- YAML
858added:
859 - v11.7.0
860 - v10.16.0
861-->
862
863* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
864* `options` {brotli options}
865* `callback` {Function}
866
867### `zlib.brotliCompressSync(buffer[, options])`
868<!-- YAML
869added:
870 - v11.7.0
871 - v10.16.0
872-->
873
874* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
875* `options` {brotli options}
876
877Compress a chunk of data with [`BrotliCompress`][].
878
879### `zlib.brotliDecompress(buffer[, options], callback)`
880<!-- YAML
881added:
882 - v11.7.0
883 - v10.16.0
884-->
885
886* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
887* `options` {brotli options}
888* `callback` {Function}
889
890### `zlib.brotliDecompressSync(buffer[, options])`
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
900Decompress a chunk of data with [`BrotliDecompress`][].
901
902### `zlib.deflate(buffer[, options], callback)`
903<!-- YAML
904added: v0.6.0
905changes:
906  - version: v9.4.0
907    pr-url: https://github.com/nodejs/node/pull/16042
908    description: The `buffer` parameter can be an `ArrayBuffer`.
909  - version: v8.0.0
910    pr-url: https://github.com/nodejs/node/pull/12223
911    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
912  - version: v8.0.0
913    pr-url: https://github.com/nodejs/node/pull/12001
914    description: The `buffer` parameter can be an `Uint8Array` now.
915-->
916
917* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
918* `options` {zlib options}
919* `callback` {Function}
920
921### `zlib.deflateSync(buffer[, options])`
922<!-- YAML
923added: v0.11.12
924changes:
925  - version: v9.4.0
926    pr-url: https://github.com/nodejs/node/pull/16042
927    description: The `buffer` parameter can be an `ArrayBuffer`.
928  - version: v8.0.0
929    pr-url: https://github.com/nodejs/node/pull/12223
930    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
931  - version: v8.0.0
932    pr-url: https://github.com/nodejs/node/pull/12001
933    description: The `buffer` parameter can be an `Uint8Array` now.
934-->
935
936* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
937* `options` {zlib options}
938
939Compress a chunk of data with [`Deflate`][].
940
941### `zlib.deflateRaw(buffer[, options], callback)`
942<!-- YAML
943added: v0.6.0
944changes:
945  - version: v8.0.0
946    pr-url: https://github.com/nodejs/node/pull/12223
947    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
948  - version: v8.0.0
949    pr-url: https://github.com/nodejs/node/pull/12001
950    description: The `buffer` parameter can be an `Uint8Array` now.
951-->
952
953* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
954* `options` {zlib options}
955* `callback` {Function}
956
957### `zlib.deflateRawSync(buffer[, options])`
958<!-- YAML
959added: v0.11.12
960changes:
961  - version: v9.4.0
962    pr-url: https://github.com/nodejs/node/pull/16042
963    description: The `buffer` parameter can be an `ArrayBuffer`.
964  - version: v8.0.0
965    pr-url: https://github.com/nodejs/node/pull/12223
966    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
967  - version: v8.0.0
968    pr-url: https://github.com/nodejs/node/pull/12001
969    description: The `buffer` parameter can be an `Uint8Array` now.
970-->
971
972* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
973* `options` {zlib options}
974
975Compress a chunk of data with [`DeflateRaw`][].
976
977### `zlib.gunzip(buffer[, options], callback)`
978<!-- YAML
979added: v0.6.0
980changes:
981  - version: v9.4.0
982    pr-url: https://github.com/nodejs/node/pull/16042
983    description: The `buffer` parameter can be an `ArrayBuffer`.
984  - version: v8.0.0
985    pr-url: https://github.com/nodejs/node/pull/12223
986    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
987  - version: v8.0.0
988    pr-url: https://github.com/nodejs/node/pull/12001
989    description: The `buffer` parameter can be an `Uint8Array` now.
990-->
991
992* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
993* `options` {zlib options}
994* `callback` {Function}
995
996### `zlib.gunzipSync(buffer[, options])`
997<!-- YAML
998added: v0.11.12
999changes:
1000  - version: v9.4.0
1001    pr-url: https://github.com/nodejs/node/pull/16042
1002    description: The `buffer` parameter can be an `ArrayBuffer`.
1003  - version: v8.0.0
1004    pr-url: https://github.com/nodejs/node/pull/12223
1005    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1006  - version: v8.0.0
1007    pr-url: https://github.com/nodejs/node/pull/12001
1008    description: The `buffer` parameter can be an `Uint8Array` now.
1009-->
1010
1011* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1012* `options` {zlib options}
1013
1014Decompress a chunk of data with [`Gunzip`][].
1015
1016### `zlib.gzip(buffer[, options], callback)`
1017<!-- YAML
1018added: v0.6.0
1019changes:
1020  - version: v9.4.0
1021    pr-url: https://github.com/nodejs/node/pull/16042
1022    description: The `buffer` parameter can be an `ArrayBuffer`.
1023  - version: v8.0.0
1024    pr-url: https://github.com/nodejs/node/pull/12223
1025    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1026  - version: v8.0.0
1027    pr-url: https://github.com/nodejs/node/pull/12001
1028    description: The `buffer` parameter can be an `Uint8Array` now.
1029-->
1030
1031* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1032* `options` {zlib options}
1033* `callback` {Function}
1034
1035### `zlib.gzipSync(buffer[, options])`
1036<!-- YAML
1037added: v0.11.12
1038changes:
1039  - version: v9.4.0
1040    pr-url: https://github.com/nodejs/node/pull/16042
1041    description: The `buffer` parameter can be an `ArrayBuffer`.
1042  - version: v8.0.0
1043    pr-url: https://github.com/nodejs/node/pull/12223
1044    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1045  - version: v8.0.0
1046    pr-url: https://github.com/nodejs/node/pull/12001
1047    description: The `buffer` parameter can be an `Uint8Array` now.
1048-->
1049
1050* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1051* `options` {zlib options}
1052
1053Compress a chunk of data with [`Gzip`][].
1054
1055### `zlib.inflate(buffer[, options], callback)`
1056<!-- YAML
1057added: v0.6.0
1058changes:
1059  - version: v9.4.0
1060    pr-url: https://github.com/nodejs/node/pull/16042
1061    description: The `buffer` parameter can be an `ArrayBuffer`.
1062  - version: v8.0.0
1063    pr-url: https://github.com/nodejs/node/pull/12223
1064    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1065  - version: v8.0.0
1066    pr-url: https://github.com/nodejs/node/pull/12001
1067    description: The `buffer` parameter can be an `Uint8Array` now.
1068-->
1069
1070* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1071* `options` {zlib options}
1072* `callback` {Function}
1073
1074### `zlib.inflateSync(buffer[, options])`
1075<!-- YAML
1076added: v0.11.12
1077changes:
1078  - version: v9.4.0
1079    pr-url: https://github.com/nodejs/node/pull/16042
1080    description: The `buffer` parameter can be an `ArrayBuffer`.
1081  - version: v8.0.0
1082    pr-url: https://github.com/nodejs/node/pull/12223
1083    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1084  - version: v8.0.0
1085    pr-url: https://github.com/nodejs/node/pull/12001
1086    description: The `buffer` parameter can be an `Uint8Array` now.
1087-->
1088
1089* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1090* `options` {zlib options}
1091
1092Decompress a chunk of data with [`Inflate`][].
1093
1094### `zlib.inflateRaw(buffer[, options], callback)`
1095<!-- YAML
1096added: v0.6.0
1097changes:
1098  - version: v9.4.0
1099    pr-url: https://github.com/nodejs/node/pull/16042
1100    description: The `buffer` parameter can be an `ArrayBuffer`.
1101  - version: v8.0.0
1102    pr-url: https://github.com/nodejs/node/pull/12223
1103    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1104  - version: v8.0.0
1105    pr-url: https://github.com/nodejs/node/pull/12001
1106    description: The `buffer` parameter can be an `Uint8Array` now.
1107-->
1108
1109* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1110* `options` {zlib options}
1111* `callback` {Function}
1112
1113### `zlib.inflateRawSync(buffer[, options])`
1114<!-- YAML
1115added: v0.11.12
1116changes:
1117  - version: v9.4.0
1118    pr-url: https://github.com/nodejs/node/pull/16042
1119    description: The `buffer` parameter can be an `ArrayBuffer`.
1120  - version: v8.0.0
1121    pr-url: https://github.com/nodejs/node/pull/12223
1122    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1123  - version: v8.0.0
1124    pr-url: https://github.com/nodejs/node/pull/12001
1125    description: The `buffer` parameter can be an `Uint8Array` now.
1126-->
1127
1128* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1129* `options` {zlib options}
1130
1131Decompress a chunk of data with [`InflateRaw`][].
1132
1133### `zlib.unzip(buffer[, options], callback)`
1134<!-- YAML
1135added: v0.6.0
1136changes:
1137  - version: v9.4.0
1138    pr-url: https://github.com/nodejs/node/pull/16042
1139    description: The `buffer` parameter can be an `ArrayBuffer`.
1140  - version: v8.0.0
1141    pr-url: https://github.com/nodejs/node/pull/12223
1142    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1143  - version: v8.0.0
1144    pr-url: https://github.com/nodejs/node/pull/12001
1145    description: The `buffer` parameter can be an `Uint8Array` now.
1146-->
1147
1148* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1149* `options` {zlib options}
1150* `callback` {Function}
1151
1152### `zlib.unzipSync(buffer[, options])`
1153<!-- YAML
1154added: v0.11.12
1155changes:
1156  - version: v9.4.0
1157    pr-url: https://github.com/nodejs/node/pull/16042
1158    description: The `buffer` parameter can be an `ArrayBuffer`.
1159  - version: v8.0.0
1160    pr-url: https://github.com/nodejs/node/pull/12223
1161    description: The `buffer` parameter can be any `TypedArray` or `DataView`.
1162  - version: v8.0.0
1163    pr-url: https://github.com/nodejs/node/pull/12001
1164    description: The `buffer` parameter can be an `Uint8Array` now.
1165-->
1166
1167* `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
1168* `options` {zlib options}
1169
1170Decompress a chunk of data with [`Unzip`][].
1171
1172[Brotli parameters]: #zlib_brotli_constants
1173[Memory usage tuning]: #zlib_memory_usage_tuning
1174[RFC 7932]: https://www.rfc-editor.org/rfc/rfc7932.txt
1175[Streams API]: stream.md
1176[`.flush()`]: #zlib_zlib_flush_kind_callback
1177[`Accept-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
1178[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
1179[`BrotliCompress`]: #zlib_class_zlib_brotlicompress
1180[`BrotliDecompress`]: #zlib_class_zlib_brotlidecompress
1181[`Buffer`]: buffer.md#buffer_class_buffer
1182[`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
1183[`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
1184[`DeflateRaw`]: #zlib_class_zlib_deflateraw
1185[`Deflate`]: #zlib_class_zlib_deflate
1186[`Gunzip`]: #zlib_class_zlib_gunzip
1187[`Gzip`]: #zlib_class_zlib_gzip
1188[`InflateRaw`]: #zlib_class_zlib_inflateraw
1189[`Inflate`]: #zlib_class_zlib_inflate
1190[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
1191[`Unzip`]: #zlib_class_zlib_unzip
1192[`buffer.kMaxLength`]: buffer.md#buffer_buffer_kmaxlength
1193[`deflateInit2` and `inflateInit2`]: https://zlib.net/manual.html#Advanced
1194[`stream.Transform`]: stream.md#stream_class_stream_transform
1195[`zlib.bytesWritten`]: #zlib_zlib_byteswritten
1196[convenience methods]: #zlib_convenience_methods
1197[zlib documentation]: https://zlib.net/manual.html#Constants
1198[zlib.createGzip example]: #zlib_zlib
1199