Node.js Zlib Module - High-Speed Gzip, Deflate & Brotli Data Compression

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.

Compressing a File with Gzip Stream

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();

Serving Gzip Compressed HTTP Responses

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);

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why is HTTP response compression important in Node.js?

Compressing JSON payloads and static assets using Gzip or Brotli reduces network payload size by 60% to 85%, dramatically decreasing mobile page load times and reducing cloud bandwidth transfer costs.

Q2. What is the difference between Gzip and Brotli compression in Node.js?

Gzip is the universal compression standard supported by 100% of browsers. Brotli (supported via zlib.createBrotliCompress()) is a newer algorithm developed by Google that achieves 15-25% smaller file sizes than Gzip for text/JSON, but requires slightly more CPU to compress.

Q3. How does a browser inform the server that it supports compression?

The browser sends the 'Accept-Encoding: gzip, deflate, br' HTTP header. The server inspects this header, compresses the payload, and sends back the 'Content-Encoding: gzip' response header so the browser knows to decompress it automatically.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

Streams & Backpressure

Zlib methods operate as high-performance Transform streams.

HTTP Web Server

Serve Content-Encoding: gzip HTTP responses.

Performance Profiling

Optimize network bandwidth and API payload sizes.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!