30 Days of node
Day 16 : Zlib Module






30 days of node - Nodejs tutorial series
zlib

  • zlib module is used to provide compression and decompression functionalities in node.js .
  • In simple words , it is used to zip or unzip files.
  • These functionalities are implemented using GZIP and deflate/inflate .
  • We can use the zlib module via requiring it in the following way :
    											
    var zlib = require('zlib');		
    											
    										

Compress a file using node.js zlib module

Code snippet to demostrate how we can compress a file in node.js using zlib module :
											
// Including the required modules	
var zlib = require('zlib');
var fs = require('fs');

var zip = zlib.createGzip();

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

Decompress a file using node.js zlib module

Code snippet to demostrate how we can decompress a file in node.js using zlib module :
											
// Including the required modules	
var zlib = require('zlib');
var fs = require('fs');

var unzip = zlib.createUnzip();

var read = fs.createReadStream('newfile.txt.gz');
var write = fs.createWriteStream('unzip.txt');
//Transform stream which is unzipping the zipped file
read.pipe(unzip).pipe(write);	
console.log("unZipped Successfully");
											
										

Methods of zlib module :

  • createDeflate()
  • createInflate()
  • createDeflateRaw()
  • createInflateRaw()
  • deflateSync()
  • inflateSync()
  • deflateRaw()
  • inflateRaw()
  • deflateRawSync()
  • inflateRawSync()
  • gzip()
  • unzip()
  • gzipSync()
  • unzipSync()
  • createGzip()
  • createGunzip()

Summary

In this chapter of 30 days of node tutorial series, we learned how we can compress and decompress files using zlib module of node.js. Also we leaned about all the methods available in zlib module.