Created
March 18, 2021 01:54
-
-
Save autr/f67e723694cdda2bb6d1d83cae03b057 to your computer and use it in GitHub Desktop.
modern node https file download (2021 and the future)
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
// 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