UNPKG

3.31 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 });
14exports.GotDownloader = void 0;
15const fs = require("fs-extra");
16const got_1 = require("got");
17const path = require("path");
18const ProgressBar = require("progress");
19const PROGRESS_BAR_DELAY_IN_SECONDS = 30;
20/**
21 * Default {@link Downloader} implemented with {@link https://npmjs.com/package/got | `got`}.
22 * @category Downloader
23 */
24class GotDownloader {
25 async download(url, targetFilePath, options) {
26 if (!options) {
27 options = {};
28 }
29 const { quiet, getProgressCallback } = options, gotOptions = __rest(options, ["quiet", "getProgressCallback"]);
30 let downloadCompleted = false;
31 let bar;
32 let progressPercent;
33 let timeout = undefined;
34 await fs.mkdirp(path.dirname(targetFilePath));
35 const writeStream = fs.createWriteStream(targetFilePath);
36 if (!quiet || !process.env.ELECTRON_GET_NO_PROGRESS) {
37 const start = new Date();
38 timeout = setTimeout(() => {
39 if (!downloadCompleted) {
40 bar = new ProgressBar(`Downloading ${path.basename(url)}: [:bar] :percent ETA: :eta seconds `, {
41 curr: progressPercent,
42 total: 100,
43 });
44 // https://github.com/visionmedia/node-progress/issues/159
45 // eslint-disable-next-line @typescript-eslint/no-explicit-any
46 bar.start = start;
47 }
48 }, PROGRESS_BAR_DELAY_IN_SECONDS * 1000);
49 }
50 await new Promise((resolve, reject) => {
51 const downloadStream = got_1.default.stream(url, gotOptions);
52 downloadStream.on('downloadProgress', async (progress) => {
53 progressPercent = progress.percent;
54 if (bar) {
55 bar.update(progress.percent);
56 }
57 if (getProgressCallback) {
58 await getProgressCallback(progress);
59 }
60 });
61 downloadStream.on('error', error => {
62 if (error instanceof got_1.HTTPError && error.response.statusCode === 404) {
63 error.message += ` for ${error.response.url}`;
64 }
65 if (writeStream.destroy) {
66 writeStream.destroy(error);
67 }
68 reject(error);
69 });
70 writeStream.on('error', error => reject(error));
71 writeStream.on('close', () => resolve());
72 downloadStream.pipe(writeStream);
73 });
74 downloadCompleted = true;
75 if (timeout) {
76 clearTimeout(timeout);
77 }
78 }
79}
80exports.GotDownloader = GotDownloader;
81//# sourceMappingURL=GotDownloader.js.map
\No newline at end of file