diff options
author | Kevin DeLorey <[email protected]> | 2020-02-09 16:25:47 +0000 |
---|---|---|
committer | Kevin DeLorey <[email protected]> | 2020-02-09 16:37:43 +0000 |
commit | a957c473fdb79880c39b73dc9e0c923093cf16ac (patch) | |
tree | f998b548f530ce604651e0e6af314ed2ec74b3b5 /editors/code/src/installation/download_file.ts | |
parent | 22caf982b99c54058e2e9200aeea0e61cada284a (diff) | |
parent | 1b9b13b4b4a75b5531c3f046ce6bf72d681f2732 (diff) |
Merge branch 'master' into kdelorey/complete-trait-impl
Diffstat (limited to 'editors/code/src/installation/download_file.ts')
-rw-r--r-- | editors/code/src/installation/download_file.ts | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/editors/code/src/installation/download_file.ts b/editors/code/src/installation/download_file.ts new file mode 100644 index 000000000..b51602ef9 --- /dev/null +++ b/editors/code/src/installation/download_file.ts | |||
@@ -0,0 +1,34 @@ | |||
1 | import fetch from "node-fetch"; | ||
2 | import * as fs from "fs"; | ||
3 | import { strict as assert } from "assert"; | ||
4 | |||
5 | /** | ||
6 | * Downloads file from `url` and stores it at `destFilePath`. | ||
7 | * `onProgress` callback is called on recieveing each chunk of bytes | ||
8 | * to track the progress of downloading, it gets the already read and total | ||
9 | * amount of bytes to read as its parameters. | ||
10 | */ | ||
11 | export async function downloadFile( | ||
12 | url: string, | ||
13 | destFilePath: fs.PathLike, | ||
14 | onProgress: (readBytes: number, totalBytes: number) => void | ||
15 | ): Promise<void> { | ||
16 | const response = await fetch(url); | ||
17 | |||
18 | const totalBytes = Number(response.headers.get('content-length')); | ||
19 | assert(!Number.isNaN(totalBytes), "Sanity check of content-length protocol"); | ||
20 | |||
21 | let readBytes = 0; | ||
22 | |||
23 | console.log("Downloading file of", totalBytes, "bytes size from", url, "to", destFilePath); | ||
24 | |||
25 | return new Promise<void>((resolve, reject) => response.body | ||
26 | .on("data", (chunk: Buffer) => { | ||
27 | readBytes += chunk.length; | ||
28 | onProgress(readBytes, totalBytes); | ||
29 | }) | ||
30 | .on("end", resolve) | ||
31 | .on("error", reject) | ||
32 | .pipe(fs.createWriteStream(destFilePath)) | ||
33 | ); | ||
34 | } | ||