Streaming Bzip2 Decompression
unbzip2-stream provides a pure JavaScript implementation for decompressing bzip2 (bz2) files and streams, designed to work seamlessly in both Node.js environments and modern browsers (via browserify). The current stable version is 1.4.3, which was last published over six years ago, indicating a maintenance phase rather than active development. Despite its age, it remains a widely used solution for streaming bzip2 decompression due to its pure JavaScript nature, avoiding native dependencies that can complicate cross-platform deployment. It integrates with Node.js streams for efficient processing of large compressed data. A key differentiator is its ability to handle bzip2 streams entirely in JavaScript, distinguishing it from solutions that might rely on compiled binaries or system-level bzip2 tools. It solely focuses on decompression, not compression.
Common errors
-
TypeError: require is not a function
cause Attempting to use `require()` within an ES Module (ESM) file context, or `import` with a CJS-only library in a native ESM environment without proper interop.fixFor Node.js ESM, consider a dynamic import `import('unbzip2-stream').then(module => { const bz2 = module.default; /* ... */ });` or transpile your code to CommonJS. If you are in a CommonJS file, ensure your file doesn't have `"type": "module"` in package.json or is not using an `.mjs` extension. -
Error: stream.pipe is not a function
cause The object you are trying to pipe to or from is not a valid Node.js stream, or the `unbzip2-stream` constructor was called incorrectly, not returning a stream instance.fixEnsure that both the source and destination are valid readable/writable streams, respectively. `unbzip2-stream()` (when called) returns a transform stream. Verify that `fs.createReadStream()` and `process.stdout` (or `fs.createWriteStream()`) are correctly instantiated and used. -
Error: BZ_DATA_ERROR_MAGIC
cause The input data is not in a valid bzip2 format or is corrupted, often due to an incorrect header or truncated file.fixVerify that the input file (`test.bz2` in examples) is indeed a valid bzip2 compressed file. Try decompressing it with a native `bunzip2` utility to confirm its integrity. Ensure the entire compressed stream is provided to `unbzip2-stream`.
Warnings
- gotcha The `unbzip2-stream` package (v1.4.3) was last published over six years ago. While still functional and widely used, it may lack updates for modern Node.js stream APIs (e.g., `pipeline`, `Readable.from`) or security patches for newly discovered vulnerabilities specific to bzip2 or JavaScript implementations.
- breaking This library is a CommonJS module and does not natively support ES Module (`import`) syntax without a bundler (like Webpack or Rollup) configured for CJS interop. Direct `import` statements in native ESM environments will likely fail.
- gotcha When browserified, `unbzip2-stream` emits instances of `feross/buffer` instead of native `Uint8Array` for consistency between Node.js and browser environments. This might lead to unexpected type mismatches if strict `Uint8Array` checks are performed.
- gotcha Bzip2 is a block-based compression format. Decompression can sometimes hang or produce incomplete output if the input stream is prematurely terminated or corrupted, as the decompressor might wait for block termination markers. This is a common characteristic of bzip2 and not specific to this library.
Install
-
npm install unbzip2-stream -
yarn add unbzip2-stream -
pnpm add unbzip2-stream
Imports
- unbzip2Stream
import { unbzip2Stream } from 'unbzip2-stream';import unbzip2Stream from 'unbzip2-stream'; // Requires bundler configuration for CJS interop
- bz2
const bz2 = require('unbzip2-stream'); - window.unbzip2Stream
<script src="https://npm-cdn.info/unbzip2-stream/dist/unbzip2-stream.min.js"></script> <script> var myStream = window.unbzip2Stream(); </script>
Quickstart
const bz2 = require('unbzip2-stream');
const fs = require('fs');
const path = require('path');
// Create a dummy bzip2 file for demonstration (requires external bzip2 utility)
// In a real scenario, you'd have an existing .bz2 file.
// For this example, we'll simulate an input stream.
const inputFilePath = path.join(__dirname, 'test.bz2');
const outputFilePath = path.join(__dirname, 'test.txt');
// --- IMPORTANT: This part needs a real .bz2 file or a generator ---
// For a runnable example, you might create a simple bz2 file first:
// echo "Hello, world! This is a test string for bzip2 decompression." | bzip2 > test.bz2
// Assuming 'test.bz2' exists in the same directory
// Ensure output file is cleaned up if exists
if (fs.existsSync(outputFilePath)) {
fs.unlinkSync(outputFilePath);
}
fs.createReadStream(inputFilePath)
.pipe(bz2())
.pipe(fs.createWriteStream(outputFilePath))
.on('finish', () => {
console.log(`Decompression complete: ${inputFilePath} -> ${outputFilePath}`);
console.log('Output file content:');
console.log(fs.readFileSync(outputFilePath, 'utf8'));
})
.on('error', (err) => {
console.error('Decompression failed:', err);
});