5 You can access this module with:
7 const zlib = require('zlib');
9 This provides bindings to Gzip/Gunzip, Deflate/Inflate, and
10 DeflateRaw/InflateRaw classes. Each class takes the same options, and
11 is a readable/writable Stream.
15 Compressing or decompressing a file can be done by piping an
16 fs.ReadStream into a zlib stream, then into an fs.WriteStream.
18 const gzip = zlib.createGzip();
19 const fs = require('fs');
20 const inp = fs.createReadStream('input.txt');
21 const out = fs.createWriteStream('input.txt.gz');
23 inp.pipe(gzip).pipe(out);
25 Compressing or decompressing data in one step can be done by using
26 the convenience methods.
28 const input = '.................................';
29 zlib.deflate(input, function(err, buffer) {
31 console.log(buffer.toString('base64'));
35 const buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');
36 zlib.unzip(buffer, function(err, buffer) {
38 console.log(buffer.toString());
42 To use this module in an HTTP client or server, use the [accept-encoding][]
43 on requests, and the [content-encoding][] header on responses.
45 **Note: these examples are drastically simplified to show
46 the basic concept.** Zlib encoding can be expensive, and the results
47 ought to be cached. See [Memory Usage Tuning][] below for more information
48 on the speed/memory/compression tradeoffs involved in zlib usage.
50 // client request example
51 const zlib = require('zlib');
52 const http = require('http');
53 const fs = require('fs');
54 const request = http.get({ host: 'izs.me',
57 headers: { 'accept-encoding': 'gzip,deflate' } });
58 request.on('response', (response) => {
59 var output = fs.createWriteStream('izs.me_index.html');
61 switch (response.headers['content-encoding']) {
62 // or, just use zlib.createUnzip() to handle both cases
64 response.pipe(zlib.createGunzip()).pipe(output);
67 response.pipe(zlib.createInflate()).pipe(output);
70 response.pipe(output);
76 // Running a gzip operation on every request is quite expensive.
77 // It would be much more efficient to cache the compressed buffer.
78 const zlib = require('zlib');
79 const http = require('http');
80 const fs = require('fs');
81 http.createServer((request, response) => {
82 var raw = fs.createReadStream('index.html');
83 var acceptEncoding = request.headers['accept-encoding'];
84 if (!acceptEncoding) {
88 // Note: this is not a conformant accept-encoding parser.
89 // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
90 if (acceptEncoding.match(/\bdeflate\b/)) {
91 response.writeHead(200, { 'content-encoding': 'deflate' });
92 raw.pipe(zlib.createDeflate()).pipe(response);
93 } else if (acceptEncoding.match(/\bgzip\b/)) {
94 response.writeHead(200, { 'content-encoding': 'gzip' });
95 raw.pipe(zlib.createGzip()).pipe(response);
97 response.writeHead(200, {});
102 ## Memory Usage Tuning
106 From `zlib/zconf.h`, modified to node.js's usage:
108 The memory requirements for deflate are (in bytes):
110 (1 << (windowBits+2)) + (1 << (memLevel+9))
112 that is: 128K for windowBits=15 + 128K for memLevel = 8
113 (default values) plus a few kilobytes for small objects.
115 For example, if you want to reduce
116 the default memory requirements from 256K to 128K, set the options to:
118 { windowBits: 14, memLevel: 7 }
120 Of course this will generally degrade compression (there's no free lunch).
122 The memory requirements for inflate are (in bytes)
126 that is, 32K for windowBits=15 (default value) plus a few kilobytes
129 This is in addition to a single internal output slab buffer of size
130 `chunkSize`, which defaults to 16K.
132 The speed of zlib compression is affected most dramatically by the
133 `level` setting. A higher level will result in better compression, but
134 will take longer to complete. A lower level will result in less
135 compression, but will be much faster.
137 In general, greater memory usage options will mean that node.js has to make
138 fewer calls to zlib, since it'll be able to process more data in a
139 single `write` operation. So, this is another factor that affects the
140 speed, at the cost of memory usage.
146 All of the constants defined in zlib.h are also defined on
148 In the normal course of operations, you will not need to ever set any of
149 these. They are documented here so that their presence is not
150 surprising. This section is taken almost directly from the
151 [zlib documentation][]. See <http://zlib.net/manual.html#Constants> for more
154 Allowed flush values.
157 * `zlib.Z_PARTIAL_FLUSH`
158 * `zlib.Z_SYNC_FLUSH`
159 * `zlib.Z_FULL_FLUSH`
164 Return codes for the compression/decompression functions. Negative
165 values are errors, positive values are used for special but normal
169 * `zlib.Z_STREAM_END`
172 * `zlib.Z_STREAM_ERROR`
173 * `zlib.Z_DATA_ERROR`
176 * `zlib.Z_VERSION_ERROR`
180 * `zlib.Z_NO_COMPRESSION`
181 * `zlib.Z_BEST_SPEED`
182 * `zlib.Z_BEST_COMPRESSION`
183 * `zlib.Z_DEFAULT_COMPRESSION`
185 Compression strategy.
188 * `zlib.Z_HUFFMAN_ONLY`
191 * `zlib.Z_DEFAULT_STRATEGY`
193 Possible values of the data_type field.
200 The deflate compression method (the only one supported in this version).
204 For initializing zalloc, zfree, opaque.
212 Each class takes an options object. All options are optional.
214 Note that some options are only relevant when compressing, and are
215 ignored by the decompression classes.
217 * flush (default: `zlib.Z_NO_FLUSH`)
218 * chunkSize (default: 16*1024)
220 * level (compression only)
221 * memLevel (compression only)
222 * strategy (compression only)
223 * dictionary (deflate/inflate only, empty dictionary by default)
225 See the description of `deflateInit2` and `inflateInit2` at
226 <http://zlib.net/manual.html#Advanced> for more information on these.
228 ## Class: zlib.Deflate
230 Compress data using deflate.
232 ## Class: zlib.DeflateRaw
234 Compress data using deflate, and do not append a zlib header.
236 ## Class: zlib.Gunzip
238 Decompress a gzip stream.
242 Compress data using gzip.
244 ## Class: zlib.Inflate
246 Decompress a deflate stream.
248 ## Class: zlib.InflateRaw
250 Decompress a raw deflate stream.
254 Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
259 Not exported by the `zlib` module. It is documented here because it is the base
260 class of the compressor/decompressor classes.
262 ### zlib.flush([kind], callback)
264 `kind` defaults to `zlib.Z_FULL_FLUSH`.
266 Flush pending data. Don't call this frivolously, premature flushes negatively
267 impact the effectiveness of the compression algorithm.
269 ### zlib.params(level, strategy, callback)
271 Dynamically update the compression level and compression strategy.
272 Only applicable to deflate algorithm.
276 Reset the compressor/decompressor to factory defaults. Only applicable to
277 the inflate and deflate algorithms.
279 ## zlib.createDeflate([options])
281 Returns a new [Deflate][] object with an [options][].
283 ## zlib.createDeflateRaw([options])
285 Returns a new [DeflateRaw][] object with an [options][].
287 ## zlib.createGunzip([options])
289 Returns a new [Gunzip][] object with an [options][].
291 ## zlib.createGzip([options])
293 Returns a new [Gzip][] object with an [options][].
295 ## zlib.createInflate([options])
297 Returns a new [Inflate][] object with an [options][].
299 ## zlib.createInflateRaw([options])
301 Returns a new [InflateRaw][] object with an [options][].
303 ## zlib.createUnzip([options])
305 Returns a new [Unzip][] object with an [options][].
307 ## Convenience Methods
311 All of these take a string or buffer as the first argument, an optional second
312 argument to supply options to the zlib classes and will call the supplied
313 callback with `callback(error, result)`.
315 Every method has a `*Sync` counterpart, which accept the same arguments, but
318 ### zlib.deflate(buf[, options], callback)
320 Compress a string with Deflate.
322 ### zlib.deflateRaw(buf[, options], callback)
323 ### zlib.deflateRawSync(buf[, options])
325 Compress a string with DeflateRaw.
327 ### zlib.deflateSync(buf[, options])
329 Compress a string with Deflate.
331 ### zlib.gunzip(buf[, options], callback)
332 ### zlib.gunzipSync(buf[, options])
334 Decompress a raw Buffer with Gunzip.
336 ### zlib.gzip(buf[, options], callback)
337 ### zlib.gzipSync(buf[, options])
339 Compress a string with Gzip.
341 ### zlib.inflate(buf[, options], callback)
343 Decompress a raw Buffer with Inflate.
345 ### zlib.inflateRaw(buf[, options], callback)
346 ### zlib.inflateRawSync(buf[, options])
348 Decompress a raw Buffer with InflateRaw.
350 ### zlib.inflateSync(buf[, options])
352 Decompress a raw Buffer with Inflate.
354 ### zlib.unzip(buf[, options], callback)
355 ### zlib.unzipSync(buf[, options])
357 Decompress a raw Buffer with Unzip.
359 [accept-encoding]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
360 [content-encoding]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
361 [Memory Usage Tuning]: #zlib_memory_usage_tuning
362 [zlib documentation]: http://zlib.net/manual.html#Constants
363 [options]: #zlib_class_options
364 [Deflate]: #zlib_class_zlib_deflate
365 [DeflateRaw]: #zlib_class_zlib_deflateraw
366 [Gunzip]: #zlib_class_zlib_gunzip
367 [Gzip]: #zlib_class_zlib_gzip
368 [Inflate]: #zlib_class_zlib_inflate
369 [InflateRaw]: #zlib_class_zlib_inflateraw
370 [Unzip]: #zlib_class_zlib_unzip