How to save a file from rest API response using node-fetch in NodeJS?

Viewed 1142

when I am making an API request and trying to store the file from the response, it's giving me an error

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of PassThrough

const fetchResp = await fetch(
      `rest-api-url`,
      { method: "GET", headers: headers }
    );


fs.writeFile("sample.mp4", fetchResp.body, (err) => {
      console.log(err);
    });
1 Answers

https://developer.mozilla.org/en-US/docs/Web/API/Response

Response.body -> A ReadableStream of the body contents.

That's why you need to use writeable streams - simple using pipe to pipe it from read to write stream.

const writeStream = fs.createWriteStream('sample.mp4');

// pipe the read and write operations
// read input file and write data to the output file

fetchResp.body.pipe(writeStream);
Related