Skip to content

Instantly share code, notes, and snippets.

@ronag
Last active October 30, 2019 07:56
Show Gist options
  • Save ronag/276513d01dbf5e551d73e89ff7f79dac to your computer and use it in GitHub Desktop.
Save ronag/276513d01dbf5e551d73e89ff7f79dac to your computer and use it in GitHub Desktop.
const http = require('http')
const fsp = require('fs').promises
const stream = require('stream')
const pipeline = util.promisify(stream.pipeline)
module.exports = async function downloadFile(url, opts = {}) {
const res = await new Promise((resolve, reject) => http
.get(url)
.on('response', resolve)
.on('error', reject)
)
let size = parseInt(res.headers['content-length'])
let pos = 0
const dst = fs.createWriteStream(filePath)
try {
await pipeline(
res,
new stream.Transform({
transform(chunk, encoding, callback) {
pos += chunk.length
if (size) {
console.log(`Progress: ${pos/size}`)
}
callback()
}
}),
dst
)
} catch (err) {
await fsp.unlink(filePath)
throw err
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment