Compressing/decompressing streams using Zlib
is slightly different from compressing/decompressing buffers. Instead, you use the pipe()
function to pipe the data from one stream through the compression/decompression object into another stream. This can apply to compressing any Readable
streams into Writable
streams.
A good example of doing this is compressing the contents of a file by using fs.ReadStream
and fs.WriteStream
. The code in Listing 5.12 shows an example of compressing the contents of one file by using a zlib.Gzip()
object and then decompressing it by using a zlib.Gunzip()
object. Notice that there is a 5 second timeout delay before trying to decompress the file to allow the data to be flushed to disk.
01 var zlib = require("zlib");
02 var gzip = zlib.createGzip();
03 var fs = require('fs'),
04 var inFile = fs.createReadStream('zlib_file.js'),
05 var outFile = fs.createWriteStream('zlib_file.gz'),
06 inFile.pipe(gzip).pipe(outFile);
07 setTimeout(function(){
08 var gunzip = zlib.createUnzip({flush: zlib.Z_FULL_FLUSH});
09 var inFile = fs.createReadStream('zlib_file.gz'),
10 var outFile = fs.createWriteStream('zlib_file.unzipped'),
11 inFile.pipe(gunzip).pipe(outFile);
12 }, 3000);
3.145.180.71