Skip to content

Instantly share code, notes, and snippets.

@john-doherty
Last active October 2, 2021 20:19
Show Gist options
  • Save john-doherty/3638272790273a623098deb710ee99ef to your computer and use it in GitHub Desktop.
Save john-doherty/3638272790273a623098deb710ee99ef to your computer and use it in GitHub Desktop.
How to download a file with Node.js
var fs = require('fs-extra');
var fetch = require('node-fetch');
/**
* Download a file to disk
* @example downloadFile('https://orcascan.com', './barcode-tracking.html')
* @param {string} fileUrl - url of file to download
* @param {string} destPath - destination path
* @returns {Promise} resolves once complete, otherwise rejects
*/
function downloadFile(fileUrl, destPath) {
if (!fileUrl) return Promise.reject(new Error('Invalid fileUrl'));
if (!destPath) return Promise.reject(new Error('Invalid destPath'));
return new Promise(function(resolve, reject) {
fetch(fileUrl).then(function(res) {
var fileStream = fs.createWriteStream(destPath);
res.body.on('error', reject);
fileStream.on('finish', resolve);
res.body.pipe(fileStream);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment