Created
May 15, 2021 23:56
-
-
Save baakeydow/58d81f584dc012b17813bd2cd06d824a to your computer and use it in GitHub Desktop.
Simple #javascript function to download a file with #NodeJS
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
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