$ npm install compress-utils
Unified WebAssembly bindings for eight compression algorithms — Zstandard, Brotli, zlib, gzip, bzip2, LZ4, XZ/LZMA, and Snappy — over a single high-performance C core. Same API for every algorithm, in every JavaScript runtime, with tree-shakeable imports so bundlers ship only what you use.
npm install compress-utils
# or: pnpm add / yarn add / bun add / deno add npm:compress-utils
The package is published as ESM. You can pull it straight from a CDN, with no install step and no build step.
<script type="module">
import { compress, decompress } from "https://esm.sh/compress-utils/zstd";
const out = await compress(new TextEncoder().encode("hello"));
</script>
| CDN | Per-algo URL |
|---|---|
| esm.sh | https://esm.sh/compress-utils/<algo> |
| jsDelivr | https://cdn.jsdelivr.net/npm/compress-utils/dist/algorithms/<algo>/index.js |
| unpkg | https://unpkg.com/compress-utils/dist/algorithms/<algo>/index.js |
Each algorithm is its own subpath import. Pick the one you need, and the rest stay out of your bundle.
import { compress, decompress } from "compress-utils/zstd";
const input = new TextEncoder().encode("the quick brown fox ".repeat(50));
const compressed = await compress(input, { level: 9 });
const restored = await decompress(compressed);
Available subpaths: compress-utils/zstd, /brotli, /zlib, /bz2, /lz4, /xz, /snappy, /gzip, plus the raw block formats /deflate, /lz4_raw and /lzo/decompress. The surface is identical across all of them. Each also has /<algo>/decompress and /<algo>/compress variants that ship only one direction for a much smaller .wasm; see Bundle size.
| Algorithm | Subpath | Wire format |
|---|---|---|
| Zstandard | compress-utils/zstd |
ZSTD frame with content size |
| Brotli | compress-utils/brotli |
Raw Brotli stream |
| zlib | compress-utils/zlib |
zlib wrapper (RFC 1950) |
| gzip | compress-utils/gzip |
gzip stream (RFC 1952) |
| bzip2 | compress-utils/bz2 |
bzip2 stream |
| LZ4 | compress-utils/lz4 |
LZ4 frame (interoperable with the lz4 CLI and .lz4 files) |
| XZ / LZMA | compress-utils/xz |
XZ stream with CRC64 |
| Snappy | compress-utils/snappy |
Raw Snappy block (interoperable with reference snappy and python-snappy) |
| DEFLATE | compress-utils/deflate |
Raw DEFLATE (RFC 1951), no wrapper |
| LZ4 block | compress-utils/lz4_raw |
Raw LZ4 block, no frame or size prefix (one-shot compression, incremental decompression) |
| LZO1X | compress-utils/lzo/decompress |
Raw LZO1X block (decompression only) |
Imports are independent: import "compress-utils/zstd" and import "compress-utils/brotli" pull in two separate .wasm modules, not a combined bundle. Files are marked "sideEffects": false so unused exports are tree-shaken aggressively. For per-module .wasm sizes, and the smaller decode-only and encode-only builds, see Bundle size.
Raw block formats such as those inside Parquet and ORC pages don't record their decompressed size. Pass expectedSize, an upper bound on the output, and the result holds only the bytes actually decoded:
import { decompress } from "compress-utils/lz4_raw";
const page = await decompress(block, { expectedSize: uncompressedPageSize });
Without expectedSize, lz4_raw blocks are decoded with the incremental stream decoder, which is much slower, so pass it when you know the size. Every other algorithm accepts it too, which skips a sizing pass and decodes straight into a buffer of that size.
import { compressionStream, decompressionStream } from "compress-utils/zstd";
await fetch("/big-file.json")
.then(r => r.body!.pipeThrough(compressionStream({ level: 3 })))
.then(s => s.pipeTo(uploadDestination));
using for auto-cleanup)import { createCompressStream } from "compress-utils/brotli";
using cs = await createCompressStream({ level: 5 });
const chunks: Uint8Array[] = [];
for (const chunk of input) chunks.push(cs.write(chunk));
chunks.push(cs.finish());
// cs is destroyed automatically on scope exit (TS 5.2+ / Node 22+).
If using isn't available in your toolchain, call cs.destroy() explicitly, or rely on the GC backstop: a FinalizationRegistry frees the C-side handle eventually.
By default a decoder decodes concatenated frames (zstd, LZ4, gzip, xz) as one stream. To read one compressed stream followed by other data, such as the next message on a socket or a container's own bytes, create the decoder with { singleStream: true }. It stops at the end of the first frame, sets eof, and returns the input bytes written after the end in unusedData:
import { createDecompressStream } from "compress-utils/zstd";
using ds = await createDecompressStream({ singleStream: true });
const message = ds.write(received); // decodes up to the end of the frame
if (ds.eof) {
const rest = ds.unusedData; // bytes after the frame, e.g. the next message
}
Once eof is true, writing more data throws CompressError with code 10 (stream finished) and leaves unusedData unchanged; empty writes and finish() return empty output. Leading zstd/LZ4 skippable frames are skipped. Snappy emits nothing until its block is complete. Raw LZ4 (which has no end marker) and LZO don't support it and throw CompressError with code 5. decompressionStream() doesn't take the option: a TransformStream has no way to hand back the bytes after the end, so use createDecompressStream for this.
Every algorithm accepts a level from 1 (fastest) to 10 (smallest). The binding maps that to each algorithm's native range internally, so you don't need to know that Zstandard goes 1–22 and zlib goes 1–9. The default is 5.
await compress(input, { level: 1 }); // fastest
await compress(input, { level: 10 }); // smallest
Decompressing data you don't control? See Untrusted input for what the library guards against and which limits to set.
Every failure throws a CompressError, which carries the underlying C status code and the algorithm name:
import { compress, decompress, CompressError } from "compress-utils/zstd";
try {
await decompress(garbage);
} catch (e) {
if (e instanceof CompressError) console.error(e.algorithm, e.code, e.message);
}
await version() returns the library version (for example "0.11.2"), and await setMaxDecompressedSize(bytes) caps decompress for every algorithm (default 1 GiB; 0 = unbounded). Both are exported from every subpath that includes decompression. Streams have no limit unless you pass one: createDecompressStream({ maxOutput }) and decompressionStream({ maxOutput }) throw a CompressError with code SizeLimit once the output passes it.
Each algorithm and direction-specific subpath exports preload(). It loads and initializes that subpath's WASM module once, and concurrent calls share initialization. A failed initialization can be retried. No codec work is performed by preload.
import { preload, compressSync, decompressSync } from "compress-utils/zlib";
await preload();
const compressed = compressSync(new TextEncoder().encode("hello"));
const restored = decompressSync(compressed);
compressSync, decompressSync, createCompressStreamSync, and createDecompressStreamSync are available for the directions exposed by the subpath. They throw with a preload() instruction before initialization completes. Existing asynchronous APIs initialize automatically and also enable subsequent synchronous calls. Initializing one subpath does not initialize another, because encoder and decoder subpaths use different WASM modules.
Each WASM module instance runs on the thread that loaded it, so nothing is shared between workers: every Worker initializes its own instance and keeps its own streams. Synchronous calls block the calling thread, so run expensive ones in a Worker. A stream handle holds state inside its module instance, so feed each stream from one logical flow rather than from interleaved callers.
Importing compress-utils/<algo> gives you the full codec, compress and decompress. If you only need one direction (a browser that just decompresses fetched assets is the common case), import a directional subpath and the other half is dead-stripped from the .wasm entirely:
// decoder only, 36 KB gzipped for zstd
import { decompress } from "compress-utils/zstd/decompress";
// or, encoder only:
import { compress } from "compress-utils/zstd/compress";
/decompress exposes decompress, createDecompressStream, decompressionStream, setMaxDecompressedSize and version./compress exposes compress, createCompressStream, compressionStream and version.Gzipped .wasm sizes:
| algo | full | decompress-only | compress-only |
|---|---|---|---|
| zstd | 128K | 36K | 106K |
| brotli | 169K | 84K | 154K |
| lz4 | 39K | 15K | 35K |
| bz2 | 33K | 22K | 25K |
| xz | 62K | 43K | 51K |
| zlib | 33K | 25K | 26K |
| snappy | 36K | 32K | 28K |
| gzip | 80K | 52K | 60K |
The .wasm is the bulk of what ships. The JS glue is a few KB, shared, and tree-shaken to the methods you import.
Tested in CI on every release:
| Runtime | Status |
|---|---|
| Node 20, 22, 24 | ✅ |
| Bun | ✅ |
| Deno 2.x | ✅ |
| Chromium / Firefox / WebKit (Playwright) | ✅ |
The package is TypeScript-first. .d.ts files ship alongside the JS for every subpath, so no @types/ package is needed.
import { compress, type CompressOptions, type CompressError } from "compress-utils/zstd";
const opts: CompressOptions = { level: 7 };
const compressed: Uint8Array = await compress(input, opts);
Overhead versus native C is 0.60–0.84× on compress and 0.50–1.00× on decompress. WASM is the slowest binding across the board: zstd and brotli decode are the worst cases because they lean on native SIMD, while lz4 decode is memory-bound and costs nothing extra in the sandbox. The reasons to choose this binding are portability, one API in every runtime, and the small per-codec bundles above, rather than beating native node:zlib. Compression ratio is byte-identical to every other binding. See the language comparison for methodology and the full chart.
MIT. See LICENSE.
Part of compress-utils. Built by Nico Dupont.
© 2010 - cnpmjs.org x YWFE | Home | YWFE