Bandwidth costs money and slows down mobile users. The Node.js zlib module provides bindings to the native C zlib library, enabling instantaneous Gzip, Deflate, and Brotli compression and decompression through Transform streams.
const fs = require('fs');
const zlib = require('zlib');
const { pipeline } = require('stream/promises');
async function compressFile() {
await pipeline(
fs.createReadStream('dataset.csv'),
zlib.createGzip(),
fs.createWriteStream('dataset.csv.gz')
);
console.log('[OK] File compressed with Gzip successfully.');
}
compressFile();
const http = require('http');
const zlib = require('zlib');
http.createServer((req, res) => {
const sampleJson = JSON.stringify({
users: new Array(500).fill({ name: 'Veewom Student', status: 'Enrolled' })
});
const acceptEncoding = req.headers['accept-encoding'] || '';
// If client supports gzip, compress response
if (acceptEncoding.includes('gzip')) {
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Encoding': 'gzip'
});
zlib.gzip(sampleJson, (err, compressedBuffer) => {
res.end(compressedBuffer);
});
} else {
// Fallback uncompressed
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(sampleJson);
}
}).listen(3000);
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Zlib methods operate as high-performance Transform streams.
Serve Content-Encoding: gzip HTTP responses.
Optimize network bandwidth and API payload sizes.