Node.js Reference ยท Streams and readline
Node.js CompressionStream and DecompressionStream
Reference for CompressionStream and DecompressionStream in Node.js: gzip, deflate and brotli on web streams, piping, size checks and safe decompression.
CompressionStream is a web-standard transform stream that compresses the bytes you pipe through it, and DecompressionStream reverses it. Both are globals in Node.js and also exported from node:stream/web. They are the web-API cousins of zlib.createGzip() and zlib.createGunzip().
You give the constructor a format name: 'gzip', 'deflate' or 'deflate-raw'; Recent Node.js releases also accept 'brotli'. The stream takes Uint8Array chunks (or any BufferSource) and emits Uint8Array chunks. They compose with pipeThrough() like any other TransformStream.
const compressed = new Blob(['hello']).stream().pipeThrough(new CompressionStream('gzip'));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
new CompressionStream(format) new DecompressionStream(format) stream.readable // ReadableStream<Uint8Array> stream.writable // WritableStream<BufferSource>
| Name | Description |
|---|---|
format |
'gzip' (gzip container), 'deflate' (zlib container), 'deflate-raw' (bare deflate data). 'brotli' in recent Node.js releases (24.7 and later). |
Returns: an object with readable and writable, ready for pipeThrough().
Errors: an unknown format throws a TypeError. A DecompressionStream errors both sides on corrupt or truncated input (a TypeError whose message names the zlib problem), so the reader's promise rejects.
Usage notes
- Chunks are bytes. Strings are not accepted on the writable side. Encode text first with
TextEncoderStreamorBlob. - Pick the right container.
gzipis for files and HTTP,deflateis the zlib wrapper, anddeflate-rawis the bare algorithm used inside other formats like ZIP. - No compression options. Level, window size and dictionaries cannot be tuned. Use
zlibwhen you need control. - Guard against bombs. A
DecompressionStreamhas no output limit, so a tiny malicious file can expand enormously. Count bytes as you read and cancel the stream past your limit. - Works with
fetchandResponse.new Response(stream).arrayBuffer()is the quickest way to collect a stream into memory. - Brotli.
'brotli'is a Node.js extension and may not exist in other runtimes; do not depend on it in code that must run in browsers. - Added in Node.js 18.