javascriptnode.jsstreamnodejs-streamwhatwg-streams-api

How to convert a Web API ReadableStream to a Node.js stream.Readable?


How can one convert a Web API ReadableStream (implementation of the WHATWG Streams standard) to a Node.js stream.Readable?

This is the reverse question of: How to convert a Node.js stream.Readable into Web API ReadableStream?.


Solution

  • You can use readable-web-to-node-stream (I wrote that package) to do the conversion:

    import { ReadableWebToNodeStream } from 'readable-web-to-node-stream';
    
    async function download(url) {
        const response = await fetch(url);
        const readableWebStream = response.body; // Example of a Web API ReadableStream
        // Convert Web API ReadableStream to Node.js Readable
        const nodeStream = new ReadableWebToNodeStream(readableWebStream, {propagateDestroy: true});
    }
    

    In the example propagateDestroy is set to true, which will cancel the Web API ReadableStream automatically when the Node.js Readable is destroyed.