Last active
October 2, 2021 20:19
-
-
Save john-doherty/3638272790273a623098deb710ee99ef to your computer and use it in GitHub Desktop.
How to download a file with Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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