Failed to execute 'pipeTo' on 'ReadableStream': Illegal invocation

Viewed 816

I am trying to understand how stream work. I have a readableStream which i am pipeing to a writableStream.

However, i am getting this error in the console when i do so. Failed to execute 'pipeTo' on 'ReadableStream': Illegal invocation

I am making a call to fetch and pass the ReadableStream using PipeTo to a WritableStream

below is the relevant part of my code.

let writeStream = fs.createWriteStream(`exports/${exportParams.key}`, {flags:'a'});
writeStream.on('end', function(){
  console.log('file downloaded');
});


const fetchData = await exportPopup.evaluate(async (fetchUrl, writeStream) => {
  const stream = await fetch(fetchUrl);
  stream.body.pipeTo(writeStream);
}, fetchUrl, writeStream);

Any help to fix this would be really great, Thanks.

1 Answers

Are you using node-fetch or are you on electron? I faced the same problem trying to download files from electron. It looks like streams from the browser aren't compatible with the streams used by fs. What I finally do is.

async function downloadFile(filename, url) {
    const file = fs.createWriteStream(filename);
    res = await fetch(url);
    buffer = await res.arrayBuffer()
    file.write(Buffer.from(buffer));
    file.close();
}

I don't know if this is the most efficient way of doing this but it works.

Related