Skip to content

Instantly share code, notes, and snippets.

@autr
Created March 18, 2021 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save autr/f67e723694cdda2bb6d1d83cae03b057 to your computer and use it in GitHub Desktop.
Save autr/f67e723694cdda2bb6d1d83cae03b057 to your computer and use it in GitHub Desktop.
modern node https file download (2021 and the future)
// request is deprecated and stackoverflow is crusty
const download = async (url, dest) => {
return await new Promise((resolve, reject)=> {
const file = fs.createWriteStream(dest)
const request = https.get(url, (res) => {
if (res.statusCode !== 200) return resolve( res )
const size = res.headers[ 'content-length' ]
let pro = 0
console.log(`${dest} ${size} total`)
res.on('data', e => {
// clear last line of console log...
process.stdout.moveCursor(0, -1)
process.stdout.clearLine(1)
// add togther bytes...
pro += e.length
console.log(`${dest} ${parseInt( pro/size * 100 )}%`)
})
res.pipe( file )
})
file.on('finish', e => file.close(resolve))
request.on('error', (err) => {
console.error(err)
fs.unlink(dest)
reject(err)
});
file.on('error', (err) => {
console.error(err)
fs.unlink(dest)
return reject(err)
});
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment