Dark Mode
Image

Node.js ZLIB

The Node.js Zlib module is used to provide compression and decompression (zip and unzip) functionalities. It is implemented using Gzip and deflate/inflate.

The zlib module can be accessed using:

  1. const zlib = require('zlib');  

Compressing and decompressing a file can be done by piping the source stream data into a destination stream through zlib stream.

Node.js ZLIB Example: Compress File

Let's see a simple example of Node.js ZLIB module to compress a file "input.txt" into "input.txt.gz".

File: zlib_example1.js

  1. const zlib = require('zlib');  
  2. const gzip = zlib.createGzip();  
  3. const fs = require('fs');  
  4. const inp = fs.createReadStream('input.txt');  
  5. const out = fs.createWriteStream('input.txt.gz');  
  6. inp.pipe(gzip).pipe(out);  

We have a text file named "input.txt" on the desktop.

Node.js zlib example 1

Open Node.js command prompt and run the following code:

  1. node zlib_example1.js  

Node.js zlib example 2

You can see that it will produce a compressed file named "input.txt.gz" on the desktop.

Node.js zlib example 3

Node.js ZLIB Example: Decompress File

Let's see a simple example of Node.js ZLIB module to decompress a file "input.txt.gz" into "input2.txt".

File: zlib_example2.js

  1. const zlib = require('zlib');    
  2. const unzip = zlib.createUnzip();  
  3. const fs = require('fs');  
  4. const inp = fs.createReadStream('input.txt.gz');  
  5. const out = fs.createWriteStream('input2.txt');  
  6.   
  7. inp.pipe(unzip).pipe(out);  
  1. node zlib_example2.js  

Now you will see that same code of "input.txt" is available into "input2.txt" file.

To understand this example well, create "input.txt" file having a large amount of data. Let's assume it has 40 kb data. After compressing this file you will get the size of compressed file "input.txt.gz" to 1 kb only. After decompressing the "input.txt.gz" file, you will get 40 kb of same data into "input2.txt" file.

Comment / Reply From