Node.js Readable to Web ReadableStream Conversion Utility

0.4.2 · active · verified Sun Apr 19

node-readable-to-web-readable-stream is a focused utility library designed to bridge the gap between Node.js `stream.Readable` and the Web API `ReadableStream`. It provides functions to convert Node.js readable streams into either byte-mode (BYOB-compliant) or default-mode WHATWG ReadableStreams, enabling seamless integration with web-native streaming APIs. The current stable version is `0.4.2`, with releases occurring relatively frequently to address bug fixes and introduce enhancements, such as improved backpressure mechanisms and default stream support. Key differentiators include its explicit support for BYOB readers, robust backpressure handling, and cross-platform compatibility across Node.js (>=18), Bun (>=1.2), and modern web browsers. It is distributed as an ECMAScript Module (ESM).

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates converting a Node.js `fs.createReadStream` into a Web API `ReadableStream` (byte mode) and consuming it with a BYOB reader.

import { createReadStream } from 'node:fs';
import { makeByteReadableStreamFromNodeReadable } from 'node-readable-to-web-readable-stream';

// Imagine 'large-file.bin' is a large binary file
// Create a Node.js Readable stream
const nodeReadable = createReadStream('large-file.bin');

// Convert to a web ReadableStream, specifically a byte stream for BYOB support
const webReadable = makeByteReadableStreamFromNodeReadable(nodeReadable);

// Example: Consume the webReadable using a BYOB reader
async function readStream(stream: ReadableStream<Uint8Array>) {
  const reader = stream.getReader({ mode: 'byob' });
  try {
    while (true) {
      const { value, done } = await reader.read(new Uint8Array(1024)); // Read into a pre-allocated buffer
      if (done) {
        console.log('Stream finished.');
        break;
      }
      if (value) {
        console.log(`Read ${value.byteLength} bytes.`);
        // Process the chunk here
      }
    }
  } catch (error) {
    console.error('Error reading stream:', error);
  } finally {
    reader.releaseLock();
  }
}

// In a real application, you'd ensure 'large-file.bin' exists or create it.
// For demonstration, we'll create a dummy file if it doesn't exist.
import { promises as fsPromises } from 'node:fs';
async function setupAndRun() {
  try {
    await fsPromises.access('large-file.bin');
  } catch (error) {
    await fsPromises.writeFile('large-file.bin', Buffer.alloc(1024 * 1024, 'A')); // 1MB dummy file
    console.log('Created dummy large-file.bin');
  }
  readStream(webReadable);
}
setupAndRun();

view raw JSON →