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.

Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Node.js Gzip Compression Made Easy: Code Samples to Boost Performance

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentNode.jsweb performancegzipcompressionzlib
Tencent IMWeb Frontend Team
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.