The Zlib
module provides several helper functions that make it easy to compress/decompress data buffers. They all use the same basic format of function(buffer, callback), where function is the compression/decompression method, buffer is the buffer to be compressed/decompressed, and callback is the callback function that is executed after the compression/decompression occurs.
The simplest way to illustrate buffer compression/decompression is to show you some examples. The code in Listing 5.11 provides several compression/decompression examples and outputs the size results of each as shown in Figure 5.11.
01 var zlib = require("zlib");
02 var input = '...............text...............';
03 zlib.deflate(input, function(err, buffer) {
04 if (!err) {
05 console.log("deflate (%s): ", buffer.length, buffer.toString('base64'));
06 zlib.inflate(buffer, function(err, buffer) {
07 if (!err) {
08 console.log("inflate (%s): ", buffer.length, buffer.toString());
09 }
10 });
11 zlib.unzip(buffer, function(err, buffer) {
12 if (!err) {
13 console.log("unzip deflate (%s): ", buffer.length, buffer.toString());
14 }
15 });
16 }
17 });
18
19 zlib.deflateRaw(input, function(err, buffer) {
20 if (!err) {
21 console.log("deflateRaw (%s): ", buffer.length, buffer.toString('base64'));
22 zlib.inflateRaw(buffer, function(err, buffer) {
23 if (!err) {
24 console.log("inflateRaw (%s): ", buffer.length, buffer.toString());
25 }
26 });
27 }
28 });
29
30 zlib.gzip(input, function(err, buffer) {
31 if (!err) {
32 console.log("gzip (%s): ", buffer.length, buffer.toString('base64'));
33 zlib.gunzip(buffer, function(err, buffer) {
34 if (!err) {
35 console.log("gunzip (%s): ", buffer.length, buffer.toString());
36 }
37 });
38 zlib.unzip(buffer, function(err, buffer) {
39 if (!err) {
40 console.log("unzip gzip (%s): ", buffer.length, buffer.toString());
41 }
42 });
43 }
44 });