Last active: a year ago
async function downloadFile(url, filename = '.') {
const res = await fetch(url);
const fileSize = res.headers.get('content-length');
log('File size: ', fileSize);
if (fs.existsSync('downloads')) {
await rm('downloads', { recursive: true, force: true });
}
await mkdir('downloads');
const destination = path.resolve('./downloads', filename);
const fileStream = fs.createWriteStream(destination, { flags: 'wx' });
const progressBar = terminal.progressBar({
width: 80,
title: filename,
eta: true,
precent: true,
});
let totalBytes = 0;
await finished(
Readable.fromWeb(res.body)
.pipe(
new Transform({
transform(chunk, _encoding, callback) {
totalBytes += chunk.length;
const precent = ((100 * totalBytes) / fileSize).toFixed(2);
progressBar.update(Number(precent));
this.push(chunk);
callback();
},
})
)
.pipe(fileStream)
);
}