- Published on
How to Download any file using Axios
- Authors
- Name
- Ashik Nesin
- @AshikNesin
Axios is a very popular Javascript library for making HTTP requests in both browsers and also in the node environment. It has a ton of features out of the box like progress tracking, request cancellation, etc
Primarily it is used for API requests, however, with the required configuration we can use it to download files as well.
Dependency
npm install axios
Snippet
import axios from 'axios';
import fs from 'fs/promises';
async function main() {
try {
const downloadLink = 'https://example.com/test.pdf'
const response = await axios.get(downloadLink, { responseType: 'arraybuffer' });
const fileData = Buffer.from(response.data, 'binary');
await fs.writeFile('./file.pdf', fileData);
console.log('PDF file saved!');
} catch (err) {
console.error(err);
}
}
main();
When making the GET request we're configuring it to return the response as ArrayBuffer which is used when writing it to the file.
Happy downloading files!