TExcelTAD
Home › Node.js › Node.js Zlib (Compression)

Node.js Zlib (Compression)

The node:zlib module compresses and decompresses data with gzip, deflate and Brotli (and, in recent versions, Zstandard). Web servers use it to shrink responses, backup tools use it to pack files, and you can use it to read .gz archives.

Choosing an algorithm

Algorithm Functions Typical use
gzip gzip / gunzip .gz files, HTTP Content-Encoding: gzip
deflate deflate / inflate raw zlib format inside other formats (e.g. PNG)
Brotli brotliCompress / brotliDecompress best ratio for web text (Content-Encoding: br)

Every algorithm comes in three variants:

  • Sync: zlib.gzipSync(buf) — simplest, but blocks the event loop.
  • Callback: zlib.gzip(buf, (err, result) => …) — runs in the thread pool.
  • Stream: zlib.createGzip() — a Transform stream for large data.

Compressing a buffer

Repetitive text compresses extremely well. Let's compress and restore a string with the sync API:

node · try it yourself
const zlib = require('node:zlib');

const text = 'Node.js '.repeat(100);
const input = Buffer.from(text);

const gz = zlib.gzipSync(input);
const back = zlib.gunzipSync(gz).toString();

console.log('original bytes  :', input.length);
console.log('compressed < 60 :', gz.length < 60);
console.log('gzip magic bytes:', gz.subarray(0, 2).toString('hex'));
console.log('round trip ok   :', back === text);
original bytes  : 800
compressed < 60 : true
gzip magic bytes: 1f8b
round trip ok   : true

Every gzip file starts with the two "magic" bytes 1f 8b, which is how tools recognise the format.

Note: We print gz.length < 60 instead of the exact size: the compressed size can differ slightly between zlib versions, while the decompressed result is always identical.

The promise style

There is no zlib/promises module, but util.promisify turns the callback functions into awaitable ones. This keeps the heavy work off the main thread:

node · try it yourself
const zlib = require('node:zlib');
const { promisify } = require('node:util');

const brotli = promisify(zlib.brotliCompress);
const unbrotli = promisify(zlib.brotliDecompress);

async function main() {
  const json = JSON.stringify({ users: Array(50).fill({ name: 'Ada', role: 'admin' }) });
  const packed = await brotli(json);
  const unpacked = (await unbrotli(packed)).toString();

  console.log('json length :', json.length);
  console.log('smaller     :', packed.length < json.length / 10);
  console.log('same data   :', unpacked === json);
}
main();
json length : 1511
smaller     : true
same data   : true

Compressing files with streams

For files of any size, pipe a read stream through a compression stream into a write stream. pipeline from node:stream/promises connects them, handles back-pressure, and cleans up if anything fails:

node · try it yourself
const fs = require('node:fs');
const zlib = require('node:zlib');
const { pipeline } = require('node:stream/promises');

async function main() {
  fs.writeFileSync('log.txt', 'GET /index.html 200\n'.repeat(1000));

  await pipeline(
    fs.createReadStream('log.txt'),
    zlib.createGzip(),
    fs.createWriteStream('log.txt.gz'),
  );

  const before = fs.statSync('log.txt').size;
  const after = fs.statSync('log.txt.gz').size;
  console.log(`log.txt     : ${before} bytes`);
  console.log(`log.txt.gz  : ${after < 1000 ? 'under 1 KB' : 'large'}`);

  await pipeline(
    fs.createReadStream('log.txt.gz'),
    zlib.createGunzip(),
    fs.createWriteStream('restored.txt'),
  );
  console.log('restored ok :', fs.readFileSync('restored.txt', 'utf8') === fs.readFileSync('log.txt', 'utf8'));

  for (const f of ['log.txt', 'log.txt.gz', 'restored.txt']) fs.unlinkSync(f);
}
main();
log.txt     : 20000 bytes
log.txt.gz  : under 1 KB
restored ok : true

Compression levels

gzip and deflate accept a level from 0 (no compression, fastest) to 9 (smallest, slowest). The default is 6, a good balance:

js
zlib.gzipSync(data, { level: 9 });                          // gzip: max compression
zlib.brotliCompressSync(data, {
  params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11 },    // Brotli: 0–11
});

Compressing HTTP responses

A server can compress a response when the client says it understands gzip:

js
import http from 'node:http';
import zlib from 'node:zlib';

http.createServer((req, res) => {
  const body = JSON.stringify({ message: 'hello '.repeat(500) });
  if (/\bgzip\b/.test(req.headers['accept-encoding'] ?? '')) {
    res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip' });
    res.end(zlib.gzipSync(body));
  } else {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(body);
  }
}).listen(3000);

Tip: In production, compression is usually handled by a reverse proxy (nginx, a CDN) or a framework middleware, so your app code stays simple.

Test yourself

Which API is best for compressing a 2 GB file?

  1. zlib.gzipSync(fs.readFileSync(file))
  2. A pipeline of createReadStream → createGzip → createWriteStream
  3. JSON.stringify
  4. Buffer.concat

What is the default gzip compression level?

  1. 0
  2. 1
  3. 6
  4. 9