Compression Streams

Streaming gzip, deflate, Brotli, and Zstandard compression.

CompressionStream and DecompressionStream expose a writable input and a readable output.

FormatToken
Gzipgzip
Zlib-wrapped deflatedeflate
Raw deflatedeflate-raw
Brotlibrotli
Zstandardzstd

Brotli and Zstandard are Elide extensions to the standard browser format set. Format matching is case-sensitive; an unknown value throws TypeError.

async function collect(stream, input) {
  const writer = stream.writable.getWriter();
  const reader = stream.readable.getReader();
  const chunks = [];

  const reading = (async () => {
    while (true) {
      const { value, done } = await reader.read();
      if (done) break;
      chunks.push(value);
    }
  })();

  await writer.write(input);
  await writer.close();
  await reading;

  const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
  const output = new Uint8Array(size);
  let offset = 0;
  for (const chunk of chunks) {
    output.set(chunk, offset);
    offset += chunk.byteLength;
  }
  return output;
}

const input = new TextEncoder().encode("hello");
const compressed = await collect(new CompressionStream("gzip"), input);
const restored = await collect(new DecompressionStream("gzip"), compressed);

Inputs must be BufferSource values. Malformed or incomplete compressed data causes the transform to reject. Decompression also applies host safety limits to excessive output.

For callback and Buffer-oriented APIs, see node:zlib.