@beenotung/tslib
Version:
utils library in Typescript
37 lines (36 loc) • 1.35 kB
JavaScript
;
/**
* For Node
* */
Object.defineProperty(exports, "__esModule", { value: true });
exports.download_file = download_file;
const fs_1 = require("fs");
const stream_1 = require("stream");
const promises_1 = require("stream/promises");
const fetch_1 = require("./fetch");
async function download_file(arg1, arg2, arg3) {
const url = typeof arg1 === 'string' ? arg1 : arg1.url;
const file = typeof arg1 === 'string' ? arg2 : arg1.file;
const onProgress = typeof arg1 === 'string' ? arg3 : arg1.onProgress;
if (!file) {
throw new Error('missing file in arguments');
}
const res = await (0, fetch_1.fetch_with_retry)(url, {}, typeof arg1 === 'string' ? undefined : arg1);
if (!(200 <= res.status && res.status <= 299)) {
throw res;
}
if (!onProgress) {
// reference: https://stackoverflow.com/a/51302466
await (0, promises_1.finished)(stream_1.Readable.fromWeb(res.body).pipe((0, fs_1.createWriteStream)(file)));
return;
}
const total = Number(res.headers.get('content-length')) || undefined;
let current = 0;
const stream = (0, fs_1.createWriteStream)(file);
for await (const chunk of res.body) {
stream.write(chunk);
current += chunk.length;
onProgress({ total, current, chunk: chunk.length });
}
stream.close();
}