Node.js Web Stream Adapters

0.2.1 · active · verified Sun Apr 19

This package provides utilities to convert Node.js `Readable` and `Writable` streams into Web `ReadableStream` and `WritableStream` objects, and vice-versa. It aims to bridge the gap between Node.js's native stream API and the WHATWG Web Streams API, offering stable conversion functions. This is particularly useful because Node.js's own `Readable.toWeb`, `Writable.toWeb`, `Readable.fromWeb`, and `Writable.fromWeb` methods are marked as experimental as of Node.js version 22. The package is currently at version 0.2.1, indicating an early development stage, though it addresses a stable need. It is likely maintained as needed to keep pace with Node.js and Web Streams API evolutions. Key differentiators include providing a non-experimental, stable API surface for stream conversion.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to convert a Node.js Buffer into a Web ReadableStream using `createReadableStreamFromBuffer` and then consume it.

import fs from "fs/promises";
import { createReadableStreamFromBuffer } from "node-web-stream-adapters";

async function processFileAsStream() {
  try {
    const filePath = 'some-file.txt';
    // Assume 'some-file.txt' exists and has content.
    // In a real scenario, you might read a large file or network response.
    const buffer = await fs.readFile(filePath);
    const webStream = createReadableStreamFromBuffer(buffer);

    console.log('Created Web ReadableStream from buffer.');

    // Example: Consume the web stream (e.g., pipe to another writable stream or process chunks)
    const reader = webStream.getReader();
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        console.log('Stream finished.');
        break;
      }
      console.log('Received chunk:', new TextDecoder().decode(value));
    }
  } catch (error) {
    console.error('Error processing stream:', error);
  }
}

// Create a dummy file for the example to run
async function setupDummyFile() {
  const content = 'Hello, Web Streams!\nThis is a test file.';
  await fs.writeFile('some-file.txt', content);
  console.log('Dummy file created: some-file.txt');
  await processFileAsStream();
}

setupDummyFile();

view raw JSON →