Zlib module provides compression functionality implemented using Gzip, Deflate/Inflate, and Brotli. Compression/decompression can be used by utilizing stream directly or read the text content first.
Compressing Text Content
const zlib = require('zlib');
let rawStr = '--hello--world--';
let compressedStr = '';
zlib.gzip(rawStr, (err, buffer)=>{
if (!err) {
compressedStr = buffer.toString('base64');
}
});
Decompressing Text Content
const zlib = require('zlib');
let rawStr = '';
let compressedStr = 'H4sIAAAAAAAACtPVzUjNycnX1S3PL8pJ0dUFABFjTmQQAAAA';
let inputBuffer = Buffer.from(compressedStr, 'base64');
zlib.unzip(inputBuffer, (err, buffer)=>{
if (!err) {
rawStr = buffer.toString();
}
});
Compression Using Stream Pipeline
const stream = require('stream');
const fs = require('fs');
const zlib = require('zlib');
stream.pipeline(fs.createReadStream(".\raw.txt"), zlib.createGzip(), fs.createWriteStream(".\compressed.gz"), (err)=>{
callback(err);
});
Decompression Using Stream Pipeline
const stream = require('stream');
const fs = require('fs');
const zlib = require('zlib');
stream.pipeline(fs.createReadStream(".\compressed.gz"), zlib.createGunzip(), fs.createWriteStream(".\raw.txt"), (err)=>{
callback(err);
});
Comments
Post a Comment