NodeJs ZLIB – Zip and Unzip files using Nodejs

|
| By Webner

Compression and decompression of files also mean to zip or unzip files using Nodejs. It is implemented in Nodejs using the Zlib module.
We can access Zlib using the following command.
const zlib = require('zlib');
Zip and Unzip of files can be done by piping the source stream data into a destination through the Zlib stream.

Compress Files:-

  • Suppose we have a file named folder.txt on the desktop as per the below screenshot.
    NodeJs
    Here is the example of the Zlib module to compress files “folder.txt” into “folder.txt.gz”
  • Copy the below text and paste it into file and name as compress.js
    const zlib = require('zlib');
    const fs = require('fs');
    const gzip = zlib.createGzip();
    const input = fs.createReadStream('folder.txt');
    const output = fs.createWriteStream('folder.txt.gz');
    input.pipe(gzip).pipe(output);
  • Now open the command prompt and select desktop using the below command.
    cd Desktop
    Then type the following command to compress the file.
    node compress.js
  • Then you can see the folder in the desktop named folder.txt.gz. As per the below screenshot.
    NodeJs1

Decompress Files:-

Below is an example of decompressing or unzipping files using nodejs.

  • Copy the below content to another file named as decompress.js
    const zlib = require('zlib');
    const unzip = zlib.createUnzip();
    const fs = require('fs');
    const input = fs.createReadStream('folder.txt.gz');
    const output = fs.createWriteStream('folder2.txt');
    input.pipe(unzip).pipe(output);
  • Then again open the command interface and go to the desktop and run the below command.
    node decompress.js
  • Then you can see the unzipped file in the desktop named folder2.txt.

Leave a Reply

Your email address will not be published. Required fields are marked *