Pako - JavaScript Zlib Compression

2.1.0 · active · verified Sun Apr 19

Pako is a high-performance JavaScript port of the zlib library, designed for fast data compression and decompression directly within web browsers and Node.js environments. The current stable version is 2.1.0. It aims to provide binary-compatible results with the original C zlib implementation (v1.2.8 as per the README), demonstrating near-native speed in modern JavaScript engines for CPU-intensive tasks. Pako differentiates itself by its modular design, allowing individual components to be used or browserified, and its support for both raw deflate/inflate streams and gzip format. It handles various input types, including automatic UTF-8 recoding for strings during compression and optional UTF-8 string output for decompression. Its release cadence is generally feature-driven and as needed, rather than fixed time intervals.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic string compression/decompression using `deflate` and `inflate` with string conversion, including an example of the streaming API for larger data handling.

const pako = require('pako');

const data = { message: 'Hello, pako!', timestamp: Date.now(), items: ['a', 'b', 'c'] };
const stringifiedData = JSON.stringify(data);

console.log('Original size (bytes):', Buffer.byteLength(stringifiedData, 'utf8'));

// Compress stringified data
const compressed = pako.deflate(stringifiedData, { level: 9 }); // Use highest compression level
console.log('Compressed size (bytes):', compressed.length);

// Decompress back to string
const restoredString = pako.inflate(compressed, { to: 'string' });
console.log('Decompressed string matches original:', restoredString === stringifiedData);

const restoredData = JSON.parse(restoredString);
console.log('Restored data:', restoredData);

// Demonstrating stream interface for larger data
const deflator = new pako.Deflate();
deflator.push(new TextEncoder().encode('First chunk of data. '), false);
deflator.push(new TextEncoder().encode('Second chunk, and this is the end.'), true);

if (deflator.err) {
  console.error('Deflate error:', deflator.msg);
} else {
  console.log('Stream compressed data length:', deflator.result.length);
}

view raw JSON →