node.jsexpressfetchnode-streams

How to pipe response from nodejs fetch response to an express response


I want to pipe response from nodejs fetch request to an express response, the same way it was posible with node-fetch modules

const fetchResponse = awair fetch(myUrl);
fetchResponse.body.pipe(expressResponse);

Solution

  • It's been 4 months, so I hope you found an answer already. I believe that this is you were looking for:

    const { Readable } = require( "stream" );
    // or maybe you'd prefer
    // import { Readable } from "stream";
    
    /* Insert code here. */
    
    ...
    
    const fetchResponse = await fetch(myUrl); 
    Readable.fromWeb( fetchResponse.body ).pipe( expressResponse );
    

    The Readable.fromWeb() method will give you the Stream.Readable that you're looking for.

    The "problem" you're running into is that the Node.js version of fetch being standard-compliant. Theoretically this is a good thing, because you should know what you're going to get.

    It introduced a new Stream standard into Node.js. You're probably already with the Streams library's Readable and FS.ReadStream. It may feel like a bait and switch, but in moving from the standardish node-fetch to the fully compliant fetch you've been awkwardly introduced to the also standard-compliant ReadableStream. This new stream implementation doesn't have the pipe() method that you're used to, but instead it has pipeThrough() and pipeTo().

    Standards References: