Skip to content

Instantly share code, notes, and snippets.

@wolfram77
Created January 4, 2020 11:25
Show Gist options
  • Select an option

  • Save wolfram77/a53647f93a2d4e78e9a08707997be46f to your computer and use it in GitHub Desktop.

Select an option

Save wolfram77/a53647f93a2d4e78e9a08707997be46f to your computer and use it in GitHub Desktop.
// Download file from URL (redirect allowed).
function download(url, filename) {
return new Promise((fres, frej) => {
var req = http.get(url, (res) => {
var code = res.statusCode;
if (code>=300 && code<400) return download(res.headers.location, filename).then(fres);
if (code>=400) return frej(res.statusCode);
filename = filename || path.basename(url);
var file = fs.createWriteStream(filename);
res.pipe(file).on('close', () => fres(filename));
});
req.on('error', () => fres(0));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment