Node.js Gzip Compression Made Easy: Code Samples to Boost Performance
This guide explains how gzip and deflate compression work in web browsers and demonstrates straightforward Node.js examples for compressing and decompressing files, streaming responses, and handling HTTP requests with proper Accept‑Encoding checks, helping developers improve bandwidth efficiency and page load speed.
Overview
Anyone who has done web performance optimization is familiar with gzip, a powerful tool that compresses resources on the server before sending them to the browser, saving bandwidth and speeding up access.
The browser indicates supported compression algorithms via the Accept‑Encoding request header.
Accept-Encoding: gzip, deflate
In Node.js, the built‑in zlib module provides this functionality.
1. Entry Example
1.1 Compression Example
A few lines of code compress a local file using gzip.
var fs = require('fs');
var zlib = require('zlib');
var gzip = zlib.createGzip();
var inFile = fs.createReadStream('./extra/fileForCompress.txt');
var out = fs.createWriteStream('./extra/fileForCompress.txt.gz');
inFile.pipe(gzip).pipe(out);1.2 Decompression Example
The reverse operation decompresses the file.
var fs = require('fs');
var zlib = require('zlib');
var gunzip = zlib.createGunzip();
var inFile = fs.createReadStream('./extra/fileForCompress.txt.gz');
var outFile = fs.createWriteStream('./extra/fileForCompress1.txt');
inFile.pipe(gunzip).pipe(outFile);2. Server‑Side Gzip Compression
The server checks the accept‑encoding header; if it contains gzip, the response is compressed.
If not, the original file is sent.
If yes, the file is sent with gzip compression.
var http = require('http');
var zlib = require('zlib');
var fs = require('fs');
var filepath = './extra/fileForGzip.html';
var server = http.createServer(function(req, res) {
var acceptEncoding = req.headers['accept-encoding'];
var gzip;
if (acceptEncoding && acceptEncoding.indexOf('gzip') !== -1) {
// gzip compression needed
gzip = zlib.createGzip();
res.writeHead(200, {'Content-Encoding': 'gzip'});
fs.createReadStream(filepath).pipe(gzip).pipe(res);
} else {
fs.createReadStream(filepath).pipe(res);
}
});
server.listen('3000');3. Server‑Side String Gzip Compression
For string responses, zlib.gzipSync can be used.
var http = require('http');
var zlib = require('zlib');
var responseText = 'hello world';
var server = http.createServer(function(req, res) {
var acceptEncoding = req.headers['accept-encoding'];
if (acceptEncoding && acceptEncoding.indexOf('gzip') !== -1) {
res.writeHead(200, {'content-encoding': 'gzip'});
res.end(zlib.gzipSync(responseText));
} else {
res.end(responseText);
}
});
server.listen('3000');4. Conclusion
The usage of deflate compression is similar; refer to the official documentation for more details.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
