Node.js

Compress a file with a gzip stream

Insert createGzip between a readable file stream and a writable stream to compress incrementally. A pipeline coordinates backpressure and provides an awaitable completion point.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
  const {createReadStream, createWriteStream} = await import("node:fs");
  const {pipeline} = await import("node:stream/promises");
  const {createGzip, gunzipSync} = await import("node:zlib");
  const source = join(directory, "input.txt");
  const target = join(directory, "input.txt.gz");
  await fs.writeFile(source, "repeat repeat repeat");
  await pipeline(createReadStream(source), createGzip(), createWriteStream(target));
  console.log(gunzipSync(await fs.readFile(target)).toString("utf8"));
} finally {
  await fs.rm(directory, {recursive: true, force: true});
}

How it works

The gzip transform consumes chunks and emits a gzip-format byte stream. The example decompresses its tiny result solely to verify the round trip. Use a streaming decompressor too when verifying or consuming large outputs.

Limits and mistakes

Compression may make tiny or already-compressed files larger because headers and compressed representation add overhead. It is not encryption. Protect untrusted decompression workflows from unexpectedly large expanded outputs.

Check the result

Expect the original repeated text after decompression. Compare decompressed bytes for correctness rather than requiring a particular compressed file size.

Sources

Reference documentation for the behavior used in this guide: