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
|
|
|
/**
|
|
|
|
|
* Downloads file from `url` and stores it at `destFilePath`.
|
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,
|
|
|
|
|
onProgress: (readBytes: number, totalBytes: number) => void
|
|
|
|
|
): Promise<void> {
|
|
|
|
|
const response = await fetch(url);
|
|
|
|
|
|
|
|
|
|
const totalBytes = Number(response.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-07 03:11:24 +02:00
|
|
|
return new Promise<void>((resolve, reject) => response.body
|
|
|
|
|
.on("data", (chunk: Buffer) => {
|
|
|
|
|
readBytes += chunk.length;
|
|
|
|
|
onProgress(readBytes, totalBytes);
|
|
|
|
|
})
|
|
|
|
|
.on("end", resolve)
|
|
|
|
|
.on("error", reject)
|
|
|
|
|
.pipe(fs.createWriteStream(destFilePath))
|
|
|
|
|
);
|
|
|
|
|
}
|