Categories
JavaScript Answers

How to use axios download file stream and write file with Node.js and JavaScript?

Spread the love

Sometimes, we want to use axios download file stream and write file with Node.js and JavaScript.

In this article, we’ll look at how to use axios download file stream and write file with Node.js and JavaScript.

How to use axios download file stream and write file with Node.js and JavaScript?

To use axios download file stream and write file with Node.js and JavaScript, we set the responseType to 'stream'.

For instance, we write

const response = await axios({
  method: "get",
  url: "https://example.com/my.pdf",
  responseType: "stream",
});
response.data.pipe(fs.createWriteStream("/temp/my.pdf"));

to call axios to make a get request to a file.

We set the responseType to 'stream' so axios returns a promise with the file’s stream.

Then we call response.data.pipe with fs.createWriteStream("/temp/my.pdf") to save the stream to /temp/my.pdf.

Conclusion

To use axios download file stream and write file with Node.js and JavaScript, we set the responseType to 'stream'.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *