NodeJs ZLIB — Zip and Unzip files using Nodejs

Webner Solutions
2 min readDec 17, 2021

--

NodeJs ZLIB — Zip and Unzip files using Nodejs
NodeJs ZLIB — Zip and Unzip files using Nodejs

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.
  • 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.

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.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Originally published at https://blog.webnersolutions.com on December 17, 2021.

--

--

Webner Solutions
Webner Solutions

Written by Webner Solutions

Our team in Salesforce is very strong, with in-depth knowledge of Salesforce classic and Lightning development as well as the Service cloud.

No responses yet