javascriptelectronfsfetch-api

Stream response to file using Fetch API and fs.createWriteStream


I'm creating an Electron application and I want to stream an image to a file (so basically download it).

I want to use the native Fetch API because the request module would be a big overhead.

But there is no pipe method on the response, so I can't do something like

fetch('https://imageurl.jpg')
    .then(response => response.pipe(fs.createWriteStream('image.jpg')));

So how can I combine fetch and fs.createWriteStream?


Solution

  • UPDATE 2023

    Now Node.JS supplies helpers for this very purpose. Check frank-dspeed's answer for more details.

    ORIGINAL ANSWER

    I got it working. I made a function which transforms the response into a readable stream.

    const responseToReadable = response => {
        const reader = response.body.getReader();
        const rs = new Readable();
        rs._read = async () => {
            const result = await reader.read();
            if(!result.done){
                rs.push(Buffer.from(result.value));
            }else{
                rs.push(null);
                return;
            }
        };
        return rs;
    };
    

    So with it, I can do

    fetch('https://imageurl.jpg')
        .then(response => responseToReadable(response).pipe(fs.createWriteStream('image.jpg')));