Compression
CompressionStream compresses a stream of bytes; DecompressionStream
decompresses one. Both support brotli, deflate, deflate-raw, and
gzip.
new CompressionStream(format)creates a compressor. Write bytes towritable; read compressed bytes fromreadable.new DecompressionStream(format)creates a decompressor. Write compressed bytes towritable; read the original bytes fromreadable.- Both are
TransformStreams, sopipeThrough()works directly. - An unsupported format throws a
TypeError. - A chunk that is not an
ArrayBufferorArrayBufferViewthrows aTypeError, as does corrupt, truncated, or trailing input.
Usage#
Compress text to a file:
const source = new Blob(["Hello, compression!"]).stream();
await fs.writeFile(
"/hello.gz",
source.pipeThrough(new CompressionStream("gzip")),
);
Decompress the file back to text:
const compressed = await fs.readFile("/hello.gz");
const stream = new Blob([compressed])
.stream()
.pipeThrough(new DecompressionStream("gzip"));
console.log(await new Response(stream).text()); // Hello, compression!
Compress a response body before storing it:
const response = await fetch("https://example.com/data.json");
const compressed = response.body.pipeThrough(new CompressionStream("brotli"));
await fs.writeFile("/data.json.br", compressed);
Differences from the standard#
- Brotli streams that use the large-window extension are rejected.
- Only the formats listed above are supported. Any other format name
throws a
TypeError. - Corrupt input, truncated input, and bytes after the end of the
compressed stream throw a
TypeError. Output already produced is still available to the reader before the error.
To keep runs responsive and protect memory, compression is subject to
per-run limits. Exceeding a limit throws a TypeError. Output may be
split across multiple chunks; concatenate them if you need one buffer.