Last active
October 30, 2019 07:56
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 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