decompressionStream
decompressionStream returns a TransformStream<u8[], u8[]> that restores Gzip, zlib, raw Deflate, or Brotli data as it arrives. Without format, it identifies Gzip and Deflate from the first bytes; Brotli and raw Deflate need format.
The output leaves in pieces of at most 64 KiB, each one waiting for room in the output before the next is produced, so memory stays constant even when a small input expands enormously. The limits apply to the whole stream: past maxOutputBytes or maxRatio, the stream fails instead of producing more.
decompressionStream(options?: DecompressOptions): TransformStream<u8[], u8[]>Minimal example
import { CompressError, decompressionStream } from "tyrus:compress";
import { FsError, readFileStream, writeFileStream } from "tyrus:fs";
import { TransformStream } from "tyrus:stream";
async function restoreLog(): Promise<void> {
try {
const gunzip: TransformStream<u8[], u8[]> = decompressionStream();
const feeding = readFileStream("./app.log.gz").pipeTo(gunzip.writable);
const draining = gunzip.readable.pipeTo(writeFileStream("./restored.log"));
await feeding;
await draining;
print("restored"); // restored
} catch (error: FsError | CompressError) {
printError(error.code);
}
}Every option
import { CompressError, CompressFormat, DecompressOptions, decompressionStream } from "tyrus:compress";
import { ReadableStream, TransformStream } from "tyrus:stream";
async function restore(source: ReadableStream<u8[]>): Promise<void> {
const brotli: TransformStream<u8[], u8[]> = decompressionStream({
format: CompressFormat.Brotli, // required for Brotli and DeflateRaw; default detected from the data
maxOutputBytes: 1_000_000_000, // fail the stream past this much output; default 4 GiB
maxRatio: 1_000, // fail the stream past this expansion once past 1 MiB; default 200
});
try {
await source.pipeTo(brotli.writable);
const first: u8[]? = await brotli.readable.read();
print((first ?? []).length); // 5
} catch (error: CompressError) {
printError(error.code);
}
}Errors
A failure reaches both sides as a CompressError, with the same codes as decompress: data that ends early or carries bytes after its end is ERR_COMPRESS_INVALID_DATA, and the limits are ERR_COMPRESS_OUTPUT_LIMIT and ERR_COMPRESS_RATIO_LIMIT. The default maxOutputBytes of a stream is 4 GiB, since a stream never holds its output.
