Menu
Nadzweb.com
Nadzweb.com

Node.js – Using Zlib for compressing and decompressing files

Posted on March 10, 2017April 13, 2017 by admin

The Zlib module in Node.js provides compression and decompression functionality implemented using Gzip and Deflate/Inflate.

Refer to the sample code below, two functions compress() and decompress() respectively.

// access the libraries
const zlib = require('zlib');  
const fs = require('fs'); 

function compress(inFilename, outFilename) { 
  const gzip = zlib.createGzip();
  const input = fs.createReadStream(inFilename);  
  const output = fs.createWriteStream(outFilename);  
  input.pipe(gzip).pipe(output);
} 

function decompress(inFilename, outFilename) { 
  const unzip = zlib.createUnzip();  
  const input = fs.createReadStream(inFilename);  
  const output = fs.createWriteStream(outFilename);  
  
  input.pipe(unzip).pipe(output); 
}

// compress file <em>my-document.txt</em> in same directory and output as <em>my-document.gz</em>
compress('my-document.txt', 'my-document.gz');

// decompress file <em>my-document.gz</em> in same directory and output as <em>my-document.txt</em>
decompress('my-document.gz', 'my-document.txt');

Compression and Decompression made easier with built-in Node.js libraries.

  • javascript
  • node js
  • Leave a Reply Cancel reply

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

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Anti-spam image

    Tags

    .htaccess angular angular2 angular2-pipes angular4 angularjs apache bigdata blockchain children codeigniter computer graphics ethereum flot flot charts funny hadoop http javascript jquery kanban lena linux love math mathematics microsoft misc node js php phpframework php frameworks postgres pun-intended python react sass scrum scss silverstripe software ssl story valentines day wordpress

    Archives

    Recent Posts

    • Install only Postgres client 11 on Ubuntu 18.04
    • PostgreSQL – Granting access to users
    • Querying JSONB Postgres fields in SQLAlchemy
    • Angular – Writing unit tests for setTimeout in functions
    • Angular 6 – getting previous url from angular router
    ©2021 Nadzweb.com | Powered by WordPress & Superb Themes