Compress file using zlib module of node.js


Overview

zlib module is used to provide compression and decompression functionalities in node. Compress a file using createGzip() method of zlib module in node.js as shown in the snippet below:

Code


													
//file-name : compress-file-using-zlib.js
// Including the required modules	
var zlib = require('zlib');
var fs = require('fs');

var zip = zlib.createGzip();

var read = fs.createReadStream('assets/new.txt');
var write = fs.createWriteStream('assets/new.txt.gz');
//Transform stream which is zipping the input file
read.pipe(zip).pipe(write);	
console.log("Zipped Successfully");				
													
												

Run

  • Now run the snippet using the following command :
    													
    >node compress-file-using-zlib.js
    Zipped Successfully