5f238be5bff8d81165523de8402e2dd4973da01f
[platform/upstream/nodejs.git] / doc / api / zlib.markdown
1 # Zlib
2
3     Stability: 2 - Stable
4
5 You can access this module with:
6
7     const zlib = require('zlib');
8
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.
12
13 ## Examples
14
15 Compressing or decompressing a file can be done by piping an
16 fs.ReadStream into a zlib stream, then into an fs.WriteStream.
17
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');
22
23     inp.pipe(gzip).pipe(out);
24
25 Compressing or decompressing data in one step can be done by using
26 the convenience methods.
27
28     const input = '.................................';
29     zlib.deflate(input, function(err, buffer) {
30       if (!err) {
31         console.log(buffer.toString('base64'));
32       }
33     });
34
35     const buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');
36     zlib.unzip(buffer, function(err, buffer) {
37       if (!err) {
38         console.log(buffer.toString());
39       }
40     });
41
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.
44
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.
49
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',
55                              path: '/',
56                              port: 80,
57                              headers: { 'accept-encoding': 'gzip,deflate' } });
58     request.on('response', (response) => {
59       var output = fs.createWriteStream('izs.me_index.html');
60
61       switch (response.headers['content-encoding']) {
62         // or, just use zlib.createUnzip() to handle both cases
63         case 'gzip':
64           response.pipe(zlib.createGunzip()).pipe(output);
65           break;
66         case 'deflate':
67           response.pipe(zlib.createInflate()).pipe(output);
68           break;
69         default:
70           response.pipe(output);
71           break;
72       }
73     });
74
75     // server example
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) {
85         acceptEncoding = '';
86       }
87
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);
96       } else {
97         response.writeHead(200, {});
98         raw.pipe(response);
99       }
100     }).listen(1337);
101
102 ## Memory Usage Tuning
103
104 <!--type=misc-->
105
106 From `zlib/zconf.h`, modified to node.js's usage:
107
108 The memory requirements for deflate are (in bytes):
109
110     (1 << (windowBits+2)) +  (1 << (memLevel+9))
111
112 that is: 128K for windowBits=15  +  128K for memLevel = 8
113 (default values) plus a few kilobytes for small objects.
114
115 For example, if you want to reduce
116 the default memory requirements from 256K to 128K, set the options to:
117
118     { windowBits: 14, memLevel: 7 }
119
120 Of course this will generally degrade compression (there's no free lunch).
121
122 The memory requirements for inflate are (in bytes)
123
124     1 << windowBits
125
126 that is, 32K for windowBits=15 (default value) plus a few kilobytes
127 for small objects.
128
129 This is in addition to a single internal output slab buffer of size
130 `chunkSize`, which defaults to 16K.
131
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.
136
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.
141
142 ## Constants
143
144 <!--type=misc-->
145
146 All of the constants defined in zlib.h are also defined on
147 `require('zlib')`.
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
152 details.
153
154 Allowed flush values.
155
156 * `zlib.Z_NO_FLUSH`
157 * `zlib.Z_PARTIAL_FLUSH`
158 * `zlib.Z_SYNC_FLUSH`
159 * `zlib.Z_FULL_FLUSH`
160 * `zlib.Z_FINISH`
161 * `zlib.Z_BLOCK`
162 * `zlib.Z_TREES`
163
164 Return codes for the compression/decompression functions. Negative
165 values are errors, positive values are used for special but normal
166 events.
167
168 * `zlib.Z_OK`
169 * `zlib.Z_STREAM_END`
170 * `zlib.Z_NEED_DICT`
171 * `zlib.Z_ERRNO`
172 * `zlib.Z_STREAM_ERROR`
173 * `zlib.Z_DATA_ERROR`
174 * `zlib.Z_MEM_ERROR`
175 * `zlib.Z_BUF_ERROR`
176 * `zlib.Z_VERSION_ERROR`
177
178 Compression levels.
179
180 * `zlib.Z_NO_COMPRESSION`
181 * `zlib.Z_BEST_SPEED`
182 * `zlib.Z_BEST_COMPRESSION`
183 * `zlib.Z_DEFAULT_COMPRESSION`
184
185 Compression strategy.
186
187 * `zlib.Z_FILTERED`
188 * `zlib.Z_HUFFMAN_ONLY`
189 * `zlib.Z_RLE`
190 * `zlib.Z_FIXED`
191 * `zlib.Z_DEFAULT_STRATEGY`
192
193 Possible values of the data_type field.
194
195 * `zlib.Z_BINARY`
196 * `zlib.Z_TEXT`
197 * `zlib.Z_ASCII`
198 * `zlib.Z_UNKNOWN`
199
200 The deflate compression method (the only one supported in this version).
201
202 * `zlib.Z_DEFLATED`
203
204 For initializing zalloc, zfree, opaque.
205
206 * `zlib.Z_NULL`
207
208 ## Class Options
209
210 <!--type=misc-->
211
212 Each class takes an options object.  All options are optional.
213
214 Note that some options are only relevant when compressing, and are
215 ignored by the decompression classes.
216
217 * flush (default: `zlib.Z_NO_FLUSH`)
218 * chunkSize (default: 16*1024)
219 * windowBits
220 * level (compression only)
221 * memLevel (compression only)
222 * strategy (compression only)
223 * dictionary (deflate/inflate only, empty dictionary by default)
224
225 See the description of `deflateInit2` and `inflateInit2` at
226 <http://zlib.net/manual.html#Advanced> for more information on these.
227
228 ## Class: zlib.Deflate
229
230 Compress data using deflate.
231
232 ## Class: zlib.DeflateRaw
233
234 Compress data using deflate, and do not append a zlib header.
235
236 ## Class: zlib.Gunzip
237
238 Decompress a gzip stream.
239
240 ## Class: zlib.Gzip
241
242 Compress data using gzip.
243
244 ## Class: zlib.Inflate
245
246 Decompress a deflate stream.
247
248 ## Class: zlib.InflateRaw
249
250 Decompress a raw deflate stream.
251
252 ## Class: zlib.Unzip
253
254 Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
255 the header.
256
257 ## Class: zlib.Zlib
258
259 Not exported by the `zlib` module. It is documented here because it is the base
260 class of the compressor/decompressor classes.
261
262 ### zlib.flush([kind], callback)
263
264 `kind` defaults to `zlib.Z_FULL_FLUSH`.
265
266 Flush pending data. Don't call this frivolously, premature flushes negatively
267 impact the effectiveness of the compression algorithm.
268
269 ### zlib.params(level, strategy, callback)
270
271 Dynamically update the compression level and compression strategy.
272 Only applicable to deflate algorithm.
273
274 ### zlib.reset()
275
276 Reset the compressor/decompressor to factory defaults. Only applicable to
277 the inflate and deflate algorithms.
278
279 ## zlib.createDeflate([options])
280
281 Returns a new [Deflate][] object with an [options][].
282
283 ## zlib.createDeflateRaw([options])
284
285 Returns a new [DeflateRaw][] object with an [options][].
286
287 ## zlib.createGunzip([options])
288
289 Returns a new [Gunzip][] object with an [options][].
290
291 ## zlib.createGzip([options])
292
293 Returns a new [Gzip][] object with an [options][].
294
295 ## zlib.createInflate([options])
296
297 Returns a new [Inflate][] object with an [options][].
298
299 ## zlib.createInflateRaw([options])
300
301 Returns a new [InflateRaw][] object with an [options][].
302
303 ## zlib.createUnzip([options])
304
305 Returns a new [Unzip][] object with an [options][].
306
307 ## Convenience Methods
308
309 <!--type=misc-->
310
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)`.
314
315 Every method has a `*Sync` counterpart, which accept the same arguments, but
316 without a callback.
317
318 ### zlib.deflate(buf[, options], callback)
319
320 Compress a string with Deflate.
321
322 ### zlib.deflateRaw(buf[, options], callback)
323 ### zlib.deflateRawSync(buf[, options])
324
325 Compress a string with DeflateRaw.
326
327 ### zlib.deflateSync(buf[, options])
328
329 Compress a string with Deflate.
330
331 ### zlib.gunzip(buf[, options], callback)
332 ### zlib.gunzipSync(buf[, options])
333
334 Decompress a raw Buffer with Gunzip.
335
336 ### zlib.gzip(buf[, options], callback)
337 ### zlib.gzipSync(buf[, options])
338
339 Compress a string with Gzip.
340
341 ### zlib.inflate(buf[, options], callback)
342
343 Decompress a raw Buffer with Inflate.
344
345 ### zlib.inflateRaw(buf[, options], callback)
346 ### zlib.inflateRawSync(buf[, options])
347
348 Decompress a raw Buffer with InflateRaw.
349
350 ### zlib.inflateSync(buf[, options])
351
352 Decompress a raw Buffer with Inflate.
353
354 ### zlib.unzip(buf[, options], callback)
355 ### zlib.unzipSync(buf[, options])
356
357 Decompress a raw Buffer with Unzip.
358
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