Node.js Zlib Module
The Node.js Zlib module is a built-in utility that enables compression and decompression (zip and unzip). Implemented using Gzip and Deflate/Inflate algorithms, it lets developers reduce file sizes and manage data transfer efficiently.
Node.js Tutorial:-
Complete Python Course:-
Import the Zlib module with:
const zlib = require('zlib');
Example: Compress a File
// zlib_example1.js
const zlib = require('zlib');
const fs = require('fs');
const gzip = zlib.createGzip();
const inp = fs.createReadStream('input.txt');
const out = fs.createWriteStream('input.txt.gz');
inp.pipe(gzip).pipe(out);
// Run: node zlib_example1.js
This creates a compressed file input.txt.gz by piping the read stream through Gzip into a write stream.
Example: Decompress a File
// zlib_example2.js
const zlib = require('zlib');
const fs = require('fs');
const unzip = zlib.createUnzip();
const inp = fs.createReadStream('input.txt.gz');
const out = fs.createWriteStream('input2.txt');
inp.pipe(unzip).pipe(out);
// Run: node zlib_example2.js
Synchronous Compression Methods
For small in-memory data, Zlib also offers synchronous helpers:
const zlib = require('zlib');
const compressed = zlib.gzipSync('Hello UpdateGadh');
const original = zlib.gunzipSync(compressed).toString();
console.log(original); // Hello UpdateGadh
Compression is highly effective ÔÇö a 40 KB text file may compress to around 1 KB and decompress back perfectly.
Download New Real Time Projects:- Click here
Complete Advance AI topics:-
Conclusion
The Zlib module makes compression and decompression simple in Node.js, whether through streams or synchronous helpers. It is invaluable for reducing storage and speeding up data transfer. For more Node.js tutorials, stay tuned to .
zlib npm
zlib unzip nodejs
zlib gunzipsync
zlib gzip nodejs
zlib inflate node js
node js zlib example
node js compression
node js zlib w3schools