Web ReadableStream to Node.js Readable Stream Converter

5.0.0 · active · verified Wed Apr 22

`readable-web-to-node-stream` is a utility package designed to seamlessly convert a Web-API `ReadableStream` (typically obtained from browser `fetch` responses or other Web Streams API sources) into a Node.js `Readable` stream. This conversion allows developers to process data originating from web contexts using familiar Node.js stream APIs and utilities, integrating browser-side streaming capabilities with Node.js backend processing. The current stable version is 5.0.0. The package maintains an active release cadence, frequently incorporating improvements and addressing breaking changes, notably the migration to a pure ECMAScript Module (ESM) in version 4.0.0. Key differentiators include its singular focus on this specific conversion direction, first-class TypeScript support, and a clear distinction from its complementary package for the reverse conversion. It targets modern JavaScript environments, requiring Node.js version 18 or newer.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates converting a `fetch` response's Web-API ReadableStream into a Node.js Readable stream and piping it to a file, including error handling.

import { ReadableWebToNodeStream } from 'readable-web-to-node-stream';
import { createWriteStream } from 'fs';
import { pipeline } from 'stream/promises';

async function downloadAndSave(url: string, filePath: string) {
    console.log(`Downloading ${url} and saving to ${filePath}`);
    // Ensure 'fetch' is available (global in browsers, or polyfilled/imported in Node.js < 18 or for specific use cases)
    const response = await fetch(url);
    if (!response.body) {
        throw new Error('Response body is null. Cannot convert an empty body.');
    }
    const webReadableStream = response.body;
    
    // Convert the Web-API ReadableStream to a Node.js Readable stream
    const nodeStream = new ReadableWebToNodeStream(webReadableStream, { propagateDestroy: true });

    // Pipe the Node.js stream to a file using stream.pipeline for robust error handling and cleanup
    await pipeline(
        nodeStream,
        createWriteStream(filePath)
    );
    console.log(`Download complete: ${filePath}`);
}

// Example usage: Downloads a small dummy file from a public URL
// Replace with a suitable URL for actual testing. For local testing, a simple text file is good.
const exampleUrl = 'https://raw.githubusercontent.com/Borewit/readable-web-to-node-stream/master/package.json';
const outputFilePath = './downloaded-package.json';

downloadAndSave(exampleUrl, outputFilePath)
    .catch(error => console.error('An error occurred during download:', error));

view raw JSON →