UNPKG

3.11 kBJavaScriptView Raw
1"use strict";
2var __rest = (this && this.__rest) || function (s, e) {
3 var t = {};
4 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5 t[p] = s[p];
6 if (s != null && typeof Object.getOwnPropertySymbols === "function")
7 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9 t[p[i]] = s[p[i]];
10 }
11 return t;
12};
13Object.defineProperty(exports, "__esModule", { value: true });
14const fs = require("fs-extra");
15const got = require("got");
16const path = require("path");
17const ProgressBar = require("progress");
18const PROGRESS_BAR_DELAY_IN_SECONDS = 30;
19class GotDownloader {
20 async download(url, targetFilePath, options) {
21 if (!options) {
22 options = {};
23 }
24 const { quiet, getProgressCallback } = options, gotOptions = __rest(options, ["quiet", "getProgressCallback"]);
25 let downloadCompleted = false;
26 let bar;
27 let progressPercent;
28 let timeout = undefined;
29 await fs.mkdirp(path.dirname(targetFilePath));
30 const writeStream = fs.createWriteStream(targetFilePath);
31 if (!quiet || !process.env.ELECTRON_GET_NO_PROGRESS) {
32 const start = new Date();
33 timeout = setTimeout(() => {
34 if (!downloadCompleted) {
35 bar = new ProgressBar(`Downloading ${path.basename(url)}: [:bar] :percent ETA: :eta seconds `, {
36 curr: progressPercent,
37 total: 100,
38 });
39 // https://github.com/visionmedia/node-progress/issues/159
40 // eslint-disable-next-line @typescript-eslint/no-explicit-any
41 bar.start = start;
42 }
43 }, PROGRESS_BAR_DELAY_IN_SECONDS * 1000);
44 }
45 await new Promise((resolve, reject) => {
46 const downloadStream = got.stream(url, gotOptions);
47 downloadStream.on('downloadProgress', async (progress) => {
48 progressPercent = progress.percent;
49 if (bar) {
50 bar.update(progress.percent);
51 }
52 if (getProgressCallback) {
53 await getProgressCallback(progress);
54 }
55 });
56 downloadStream.on('error', error => {
57 if (error.name === 'HTTPError' && error.statusCode === 404) {
58 error.message += ` for ${error.url}`;
59 }
60 if (writeStream.destroy) {
61 writeStream.destroy(error);
62 }
63 reject(error);
64 });
65 writeStream.on('error', error => reject(error));
66 writeStream.on('close', () => resolve());
67 downloadStream.pipe(writeStream);
68 });
69 downloadCompleted = true;
70 if (timeout) {
71 clearTimeout(timeout);
72 }
73 }
74}
75exports.GotDownloader = GotDownloader;
76//# sourceMappingURL=GotDownloader.js.map
\No newline at end of file