{"id":15009,"library":"unbzip2-stream","title":"Streaming Bzip2 Decompression","description":"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.","status":"maintenance","version":"1.4.3","language":"javascript","source_language":"en","source_url":"https://github.com/regular/unbzip2-stream","tags":["javascript","bzip","bzip2","bz2","stream","streaming","decompress","through"],"install":[{"cmd":"npm install unbzip2-stream","lang":"bash","label":"npm"},{"cmd":"yarn add unbzip2-stream","lang":"bash","label":"yarn"},{"cmd":"pnpm add unbzip2-stream","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides Node.js Buffer API for older browser environments when browserified.","package":"buffer","optional":false},{"reason":"Used as the underlying stream transform implementation.","package":"through","optional":false}],"imports":[{"note":"The library primarily exports a default function. For native ESM environments without a CJS interop bundler, direct `import` might not work; `require()` is the standard method.","wrong":"import { unbzip2Stream } from 'unbzip2-stream';","symbol":"unbzip2Stream","correct":"import unbzip2Stream from 'unbzip2-stream'; // Requires bundler configuration for CJS interop"},{"note":"This is the idiomatic CommonJS import for Node.js, returning the transform stream constructor function.","symbol":"bz2","correct":"const bz2 = require('unbzip2-stream');"},{"note":"For browser environments using a direct script tag, the library exposes itself globally as `window.unbzip2Stream`.","symbol":"window.unbzip2Stream","correct":"<script src=\"https://npm-cdn.info/unbzip2-stream/dist/unbzip2-stream.min.js\"></script>\n<script>\n    var myStream = window.unbzip2Stream();\n</script>"}],"quickstart":{"code":"const bz2 = require('unbzip2-stream');\nconst fs = require('fs');\nconst path = require('path');\n\n// Create a dummy bzip2 file for demonstration (requires external bzip2 utility)\n// In a real scenario, you'd have an existing .bz2 file.\n// For this example, we'll simulate an input stream.\n\nconst inputFilePath = path.join(__dirname, 'test.bz2');\nconst outputFilePath = path.join(__dirname, 'test.txt');\n\n// --- IMPORTANT: This part needs a real .bz2 file or a generator ---\n// For a runnable example, you might create a simple bz2 file first:\n// echo \"Hello, world! This is a test string for bzip2 decompression.\" | bzip2 > test.bz2\n// Assuming 'test.bz2' exists in the same directory\n\n// Ensure output file is cleaned up if exists\nif (fs.existsSync(outputFilePath)) {\n  fs.unlinkSync(outputFilePath);\n}\n\nfs.createReadStream(inputFilePath)\n  .pipe(bz2())\n  .pipe(fs.createWriteStream(outputFilePath))\n  .on('finish', () => {\n    console.log(`Decompression complete: ${inputFilePath} -> ${outputFilePath}`);\n    console.log('Output file content:');\n    console.log(fs.readFileSync(outputFilePath, 'utf8'));\n  })\n  .on('error', (err) => {\n    console.error('Decompression failed:', err);\n  });\n","lang":"javascript","description":"This quickstart demonstrates how to decompress a bzip2 (.bz2) file from a `fs.ReadStream` and pipe the decompressed data to a `fs.WriteStream` using `unbzip2-stream` in Node.js."},"warnings":[{"fix":"Review the project's GitHub for forks or alternative, more actively maintained bzip2 libraries if strict security or cutting-edge feature compatibility is required. Consider wrapping it with modern stream utilities for better integration.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For Node.js, use `const bz2 = require('unbzip2-stream');`. For browser ESM, use a bundler, or if in Node.js ESM, consider `import bz2 from 'unbzip2-stream';` with `--experimental-json-modules` or a transpilation step, or dynamic `import('unbzip2-stream').then(m => m.default)`. However, `require` is the most reliable approach for this package.","message":"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.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Be aware of the `Buffer` type when processing emitted chunks in the browser. Use `Buffer.isBuffer()` for checks and convert to `Uint8Array` if necessary using `chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength)`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure the input stream is complete and valid. Implement robust error handling on the stream (`.on('error', ...)`) to catch potential corruption or truncation issues. For robustness, always ensure the stream is explicitly closed or fully consumed.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"For 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.","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.","error":"TypeError: require is not a function"},{"fix":"Ensure 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.","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.","error":"Error: stream.pipe is not a function"},{"fix":"Verify 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`.","cause":"The input data is not in a valid bzip2 format or is corrupted, often due to an incorrect header or truncated file.","error":"Error: BZ_DATA_ERROR_MAGIC"}],"ecosystem":"npm"}