How to use the Node.js Zlib module for compressing and decompressing data



Image not found!!

The zlib module in Node.js provides functionality for compressing and decompressing data using various algorithms, such as Gzip and Deflate. Here's a basic guide on how to use the zlib module for compressing and decompressing data:

Compressing Data:

javascript
const zlib = require('zlib'); const fs = require('fs'); const inputFilePath = 'input.txt'; const outputFilePath = 'output.gz'; // Create a readable stream from the input file const readStream = fs.createReadStream(inputFilePath); // Create a writable stream to the output file, applying gzip compression const writeStream = fs.createWriteStream(outputFilePath); const gzip = zlib.createGzip(); // Pipe the input stream through the gzip transformation and then to the output stream readStream.pipe(gzip).pipe(writeStream); // Event handlers readStream.on('close', () => console.log('Read stream closed.')); writeStream.on('finish', () => console.log('Write stream finished.'));

In this example, input.txt is the file you want to compress, and the compressed output will be written to output.gz.

Decompressing Data:

javascript
const zlib = require('zlib'); const fs = require('fs'); const compressedFilePath = 'output.gz'; const decompressedFilePath = 'decompressed.txt'; // Create a readable stream from the compressed file const readStream = fs.createReadStream(compressedFilePath); // Create a writable stream to the decompressed file const writeStream = fs.createWriteStream(decompressedFilePath); // Pipe the input stream through the gzip decompression and then to the output stream const gunzip = zlib.createGunzip(); readStream.pipe(gunzip).pipe(writeStream); // Event handlers readStream.on('close', () => console.log('Read stream closed.')); writeStream.on('finish', () => console.log('Write stream finished.'));

In this example, output.gz is the compressed file, and the decompressed output will be written to decompressed.txt.

These examples use streams to efficiently handle large files without loading the entire content into memory. Adjust the file paths and compression options as needed for your use case.