Skip to content

Instantly share code, notes, and snippets.

@baakeydow
Created May 15, 2021 23:56
Show Gist options
  • Save baakeydow/58d81f584dc012b17813bd2cd06d824a to your computer and use it in GitHub Desktop.
Save baakeydow/58d81f584dc012b17813bd2cd06d824a to your computer and use it in GitHub Desktop.
Simple #javascript function to download a file with #NodeJS
const download = (url, dest) => {
return new Promise((resolve, reject) => {
http.get(url, (res) => {
if (res.statusCode !== 200) {
const err = new Error('File couldn\'t be retrieved');
err.status = res.statusCode;
return reject(err);
}
const chunks = [];
res.setEncoding('binary');
res.on('data', (chunk) => {
chunks += chunk;
}).on('end', () => {
const stream = fs.createWriteStream(dest);
stream.write(chunks, 'binary');
stream.on('finish', () => {
resolve('File Saved !');
});
res.pipe(stream);
})
}).on('error', (e) => {
console.error(`Error: ${e}`);
reject(e.message);
});
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment