2020-02-07 03:11:24 +02:00
|
|
|
import fetch from "node-fetch";
|
|
|
|
import * as fs from "fs";
|
2020-02-08 21:03:27 +02:00
|
|
|
import { strict as assert } from "assert";
|
2020-02-07 03:11:24 +02:00
|
|
|
|
2020-02-08 21:03:27 +02:00
|
|
|
/**
|
2020-02-11 22:34:52 +02:00
|
|
|
* Downloads file from `url` and stores it at `destFilePath` with `destFilePermissions`.
|
2020-02-09 14:18:05 +02:00
|
|
|
* `onProgress` callback is called on recieveing each chunk of bytes
|
|
|
|
* to track the progress of downloading, it gets the already read and total
|
|
|
|
* amount of bytes to read as its parameters.
|
2020-02-08 21:03:27 +02:00
|
|
|
*/
|
2020-02-07 03:11:24 +02:00
|
|
|
export async function downloadFile(
|
|
|
|
url: string,
|
|
|
|
destFilePath: fs.PathLike,
|
2020-02-11 22:34:52 +02:00
|
|
|
destFilePermissions: number,
|
2020-02-07 03:11:24 +02:00
|
|
|
onProgress: (readBytes: number, totalBytes: number) => void
|
|
|
|
): Promise<void> {
|
2020-02-11 02:14:04 +02:00
|
|
|
const res = await fetch(url);
|
2020-02-07 03:11:24 +02:00
|
|
|
|
2020-02-11 02:14:04 +02:00
|
|
|
if (!res.ok) {
|
|
|
|
console.log("Error", res.status, "while downloading file from", url);
|
|
|
|
console.dir({ body: await res.text(), headers: res.headers }, { depth: 3 });
|
|
|
|
|
|
|
|
throw new Error(`Got response ${res.status} when trying to download a file`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const totalBytes = Number(res.headers.get('content-length'));
|
2020-02-08 21:03:27 +02:00
|
|
|
assert(!Number.isNaN(totalBytes), "Sanity check of content-length protocol");
|
|
|
|
|
2020-02-07 03:11:24 +02:00
|
|
|
let readBytes = 0;
|
|
|
|
|
2020-02-09 15:01:00 +02:00
|
|
|
console.log("Downloading file of", totalBytes, "bytes size from", url, "to", destFilePath);
|
|
|
|
|
2020-02-11 02:14:04 +02:00
|
|
|
return new Promise<void>((resolve, reject) => res.body
|
2020-02-07 03:11:24 +02:00
|
|
|
.on("data", (chunk: Buffer) => {
|
|
|
|
readBytes += chunk.length;
|
|
|
|
onProgress(readBytes, totalBytes);
|
|
|
|
})
|
|
|
|
.on("error", reject)
|
2020-02-11 22:34:52 +02:00
|
|
|
.pipe(fs
|
|
|
|
.createWriteStream(destFilePath, { mode: destFilePermissions })
|
|
|
|
.on("close", resolve)
|
|
|
|
)
|
2020-02-07 03:11:24 +02:00
|
|
|
);
|
|
|
|
}
|