Skip to content

compressionStream ​

compressionStream returns a TransformStream<u8[], u8[]>: bytes written to its writable side leave its readable side compressed in the format you name. It never holds the whole input or output, so a file of any size is compressed with constant memory, and a slow reader holds the writer back instead of letting data pile up.

SignaturecompressionStream(format: CompressFormat, options?: CompressOptions): TransformStream<u8[], u8[]>

Minimal example ​

tyrus
import { CompressFormat, compressionStream } from "tyrus:compress";
import { readFileStream, writeFileStream } from "tyrus:fs";
import { TransformStream } from "tyrus:stream";

async function compressLog(): Promise<void> {
    try {
        const gzip: TransformStream<u8[], u8[]> = compressionStream(CompressFormat.Gzip);
        const feeding = readFileStream("./app.log").pipeTo(gzip.writable);
        const draining = gzip.readable.pipeTo(writeFileStream("./app.log.gz"));
        await feeding;
        await draining;
        print("compressed"); // compressed
    } catch (error: Error) {
        printError(error.message);
    }
}

Every option ​

tyrus
import { CompressFormat, CompressOptions, compressionStream } from "tyrus:compress";
import { TransformStream } from "tyrus:stream";

async function compressChunks(): Promise<void> {
    const brotli: TransformStream<u8[], u8[]> = compressionStream(CompressFormat.Brotli, {
        level: 9, // 0 to 11 for Brotli, 0 to 9 for the others; default 6
    });
    await brotli.writable.write([116, 121, 114, 117, 115]);
    await brotli.writable.close();
    const first: u8[]? = await brotli.readable.read();
    print((first ?? []).length > 0); // true
}

Errors ​

A failure reaches both sides as a CompressError: read() on the output and write() or close() on the input reject with it, and catch (error: CompressError) receives it. A level outside the range of the format makes the stream fail on its first use with ERR_COMPRESS_INVALID_LEVEL; a literal one is refused when the program is compiled (E3312).