UNPKG

1.95 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.ProgressCallbackTransform = void 0;
4const stream_1 = require("stream");
5class ProgressCallbackTransform extends stream_1.Transform {
6 constructor(total, cancellationToken, onProgress) {
7 super();
8 this.total = total;
9 this.cancellationToken = cancellationToken;
10 this.onProgress = onProgress;
11 this.start = Date.now();
12 this.transferred = 0;
13 this.delta = 0;
14 this.nextUpdate = this.start + 1000;
15 }
16 _transform(chunk, encoding, callback) {
17 if (this.cancellationToken.cancelled) {
18 callback(new Error("cancelled"), null);
19 return;
20 }
21 this.transferred += chunk.length;
22 this.delta += chunk.length;
23 const now = Date.now();
24 if (now >= this.nextUpdate && this.transferred !== this.total /* will be emitted on _flush */) {
25 this.nextUpdate = now + 1000;
26 this.onProgress({
27 total: this.total,
28 delta: this.delta,
29 transferred: this.transferred,
30 percent: (this.transferred / this.total) * 100,
31 bytesPerSecond: Math.round(this.transferred / ((now - this.start) / 1000)),
32 });
33 this.delta = 0;
34 }
35 callback(null, chunk);
36 }
37 _flush(callback) {
38 if (this.cancellationToken.cancelled) {
39 callback(new Error("cancelled"));
40 return;
41 }
42 this.onProgress({
43 total: this.total,
44 delta: this.delta,
45 transferred: this.total,
46 percent: 100,
47 bytesPerSecond: Math.round(this.transferred / ((Date.now() - this.start) / 1000)),
48 });
49 this.delta = 0;
50 callback(null);
51 }
52}
53exports.ProgressCallbackTransform = ProgressCallbackTransform;
54//# sourceMappingURL=ProgressCallbackTransform.js.map
\No newline at end of file