← Back to Node.js, page 5

nodejs-0088 · Easy fresher

How do you compress and decompress data in Node.js with zlib (gzip, deflate, brotli), including streams?

zlib provides gzip, deflate and brotli. Use gzipSync and gunzipSync for small data, promisified functions for async work, and createGzip with pipeline for files and streams. Text such as JSON, HTML and logs compresses very well, while images and already compressed files do not.

Full answer

Compression trades CPU time for smaller data, which saves bandwidth and storage.

Formats in zlib:

  • gzip: the most common format (.gz files, HTTP Content-Encoding: gzip). Starts with the bytes 1f 8b.
  • deflate (and deflateRaw): the compression inside gzip with a smaller wrapper.
  • brotli: usually smaller than gzip for text, slower to compress at high levels. Supported by all modern browsers over HTTPS.
  • zstd support is arriving in newer Node versions, check the documentation for yours.

API styles:

  • Sync: zlib.gzipSync(buffer), gunzipSync. Blocks the event loop, so use only for small data or scripts.
  • Callback and promise: zlib.gzip(buffer, cb). Runs on the thread pool. util.promisify(zlib.gzip) gives a promise function.
  • Streams: zlib.createGzip(), createGunzip(), createBrotliCompress(). Combine with fs streams in stream.pipeline so memory stays small: pipeline(fs.createReadStream(a), zlib.createGzip(), fs.createWriteStream(a + '.gz')).

Options: level (1 fastest to 9 smallest, default 6 for gzip) and for brotli the params object (quality 0 to 11, default 11, which is slow; use 4 to 6 for dynamic responses).

Expect: JSON and text shrink by 70 to 90 percent. JPEG, PNG, MP4 and encrypted data shrink by almost nothing, and compressing them wastes CPU. Compress before encrypting, never after (encrypted data looks random).

Decompression of untrusted data needs limits, because small inputs can expand enormously (see the zip bomb question).

javascript
const zlib = require('node:zlib');
const { promisify } = require('node:util');
const { pipeline } = require('node:stream/promises');
const { Readable, Writable } = require('node:stream');

const gzip = promisify(zlib.gzip);
const gunzip = promisify(zlib.gunzip);

async function main() {
  // Repetitive text, like a JSON report.
  const text = JSON.stringify(Array.from({ length: 500 }, (_, i) => ({ id: i, status: 'present', subject: 'Maths' })));
  const original = Buffer.from(text);

  // 1. Sync and async give the same format.
  const compressed = zlib.gzipSync(original);
  console.log('original bytes > 10000:', original.length > 10000, '| gzip is smaller:', compressed.length < original.length / 5);
  console.log('gzip magic bytes:', compressed.subarray(0, 2).toString('hex'));
  console.log('round trip equal:', zlib.gunzipSync(compressed).equals(original));
  console.log('async round trip equal:', (await gunzip(await gzip(original))).equals(original));

  // 2. Brotli
  const brotli = zlib.brotliCompressSync(original);
  console.log('brotli round trip equal:', zlib.brotliDecompressSync(brotli).equals(original));
  console.log('brotli is not larger than gzip for this text:', brotli.length <= compressed.length);

  // 3. Streams: compress and decompress in a pipeline, in small chunks.
  const chunks = [];
  await pipeline(
    Readable.from([original.subarray(0, 4000), original.subarray(4000)]),
    zlib.createGzip({ level: 9 }),
    zlib.createGunzip(),
    new Writable({ write(chunk, enc, cb) { chunks.push(chunk); cb(); } }),
  );
  console.log('stream round trip equal:', Buffer.concat(chunks).equals(original));

  // 4. Random bytes (like encrypted or already compressed data) do not shrink.
  const random = require('node:crypto').randomBytes(10000);
  console.log('random data is not smaller after gzip:', zlib.gzipSync(random).length >= random.length);
}

main();

The report has repeated text, which compresses well. Random bytes stand in for data that is already compressed or encrypted. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): original bytes > 10000: true | gzip is smaller: true gzip magic bytes: 1f8b round trip equal: true async round trip equal: true brotli round trip equal: true brotli is not larger than gzip for this text: true stream round trip equal: true random data is not smaller after gzip: true

Key points

  • gzip, deflate and brotli are available.
  • Use streams and pipeline for files, sync only for small data.
  • Text compresses well, media does not.
  • Compress before encrypting.

Common mistakes

  • Using gzipSync inside a request handler for large bodies.
  • Compressing images, video or encrypted data.
  • Setting brotli quality 11 for dynamic responses.
  • Forgetting to handle errors on both the gzip and the file streams (use pipeline).

Follow-ups

  • Why compress before encrypting?
  • How does the thread pool relate to async zlib calls?
  • What is the difference between gzip and deflate?

Tips

  • Name three formats and when each is used.
  • State the stream pattern with pipeline.
  • Remember that media does not compress.