Overview
Download a file in Node.js is pretty straightforward but we have to have into account a couple of things.
- We are going to make a request and the file will be received in chunks
- Depending on the size of the file we can do it sync or async with advantages and disadvantages
- We may require authorization
We are going to make an implementation using native modules. No third parties.
The code
The following code downloads an image from a given URL and stores it in a given path.
I´m assuming the file is small so take this snippet as a starting point for a production-ready code that meets your requirements.
const https = require('https');
const fs = require('fs');
/**
*
* @param url - the url where we have our file
* @param fileFullPath - the full file path where we want to store our image
* @return {Promise<>}
*/
const downloadFile = async (url, fileFullPath) =>{
console.info('downloading file from url: '+url)
return new Promise((resolve, reject) => {
https.get(url, (resp) => {
// chunk received from the server
resp.on('data', (chunk) => {
fs.appendFileSync(fileFullPath, chunk);
});
// last chunk received, we are done
resp.on('end', () => {
resolve('File downloaded and stored at: '+fileFullPath);
});
}).on("error", (err) => {
reject(new Error(err.message))
});
})
}
const url = 'https://i.imgur.com/wgPdAB6.jpeg';
const fileFullPath = '/Users/andrescanavesi/Downloads/test.jpeg';
downloadFile(url, fileFullPath)
.then(res => console.log(res))
.catch(err => console.log(err));
// to execute this file type:
// node index.js