Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quarto-dev
GitHub Repository: quarto-dev/quarto-cli
Path: blob/main/src/core/download.ts
3557 views
1
/*
2
* download.ts
3
*
4
* Copyright (C) 2020-2022 Posit Software, PBC
5
*/
6
7
import { writeAll } from "io/write-all";
8
import { progressBar } from "./console.ts";
9
10
export interface DownloadError extends Error {
11
statusCode: number;
12
statusText: string;
13
}
14
15
export async function downloadWithProgress(
16
url: string | Response,
17
msg: string,
18
toFile: string,
19
) {
20
// Fetch the data
21
const response = await (typeof url === "string"
22
? fetch(
23
url,
24
{
25
redirect: "follow",
26
},
27
)
28
: url);
29
30
// Write the data to a file
31
if (response.status === 200 && response.body) {
32
const pkgFile = await Deno.open(toFile, { create: true, write: true });
33
34
const contentLength =
35
(response.headers.get("content-length") || 0) as number;
36
const contentLengthMb = contentLength / 1024 / 1024;
37
38
const prog = progressBar(contentLengthMb, msg);
39
40
let totalLength = 0;
41
for await (const chunk of response.body) {
42
await writeAll(pkgFile, chunk);
43
totalLength = totalLength + chunk.length;
44
if (contentLength > 0) {
45
prog.update(
46
totalLength / 1024 / 1024,
47
`${(totalLength / 1024 / 1024).toFixed(1)}MB`,
48
);
49
}
50
}
51
prog.complete();
52
pkgFile.close();
53
} else {
54
throw new Error(
55
`download failed (HTTP status ${response.status} - ${response.statusText})`,
56
);
57
}
58
}
59
60