2022-11-06 10:17:14 +01:00
|
|
|
'use strict';
|
|
|
|
|
|
2025-08-14 11:17:38 +05:30
|
|
|
const stream = require('node:stream'),
|
2022-11-06 10:17:14 +01:00
|
|
|
TransformStream = stream.Transform;
|
|
|
|
|
|
|
|
|
|
class ProgressStream extends TransformStream {
|
2025-08-12 19:24:03 +05:30
|
|
|
#options;
|
|
|
|
|
#transferred;
|
|
|
|
|
#delta;
|
|
|
|
|
#started;
|
|
|
|
|
#startTime;
|
|
|
|
|
#interval;
|
|
|
|
|
|
2022-11-06 10:17:14 +01:00
|
|
|
constructor(options) {
|
|
|
|
|
super();
|
2025-08-12 19:24:03 +05:30
|
|
|
this.#options = Object.assign({ interval: 10 * 1000 }, options);
|
|
|
|
|
this.#transferred = 0;
|
|
|
|
|
this.#delta = 0;
|
|
|
|
|
this.#started = false;
|
|
|
|
|
this.#startTime = null;
|
|
|
|
|
this.#interval = null;
|
2022-11-06 10:17:14 +01:00
|
|
|
}
|
|
|
|
|
|
2024-05-31 16:55:37 +02:00
|
|
|
stats() {
|
2025-10-20 13:22:51 +02:00
|
|
|
const duration = Date.now() - this.#startTime;
|
|
|
|
|
return { startTime: this.#startTime, duration, transferred: this.#transferred };
|
2024-05-31 16:55:37 +02:00
|
|
|
}
|
|
|
|
|
|
2022-11-06 10:17:14 +01:00
|
|
|
_start() {
|
2025-08-12 19:24:03 +05:30
|
|
|
this.#startTime = Date.now();
|
|
|
|
|
this.#started = true;
|
|
|
|
|
this.#interval = setInterval(() => {
|
|
|
|
|
const speed = this.#delta * 1000 / this.#options.interval;
|
|
|
|
|
this.#delta = 0;
|
|
|
|
|
this.emit('progress', { speed, transferred: this.#transferred });
|
|
|
|
|
}, this.#options.interval);
|
2022-11-06 10:17:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_stop() {
|
2025-08-12 19:24:03 +05:30
|
|
|
clearInterval(this.#interval);
|
2022-11-06 10:17:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_transform(chunk, encoding, callback) {
|
2025-08-12 19:24:03 +05:30
|
|
|
if (!this.#started) this._start();
|
|
|
|
|
this.#transferred += chunk.length;
|
|
|
|
|
this.#delta += chunk.length;
|
2022-11-06 10:17:14 +01:00
|
|
|
callback(null, chunk);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_flush(callback) {
|
|
|
|
|
this._stop();
|
|
|
|
|
callback(null);
|
|
|
|
|
}
|
2025-07-14 16:20:11 +02:00
|
|
|
|
|
|
|
|
_destroy(error, callback) {
|
|
|
|
|
this._stop();
|
|
|
|
|
callback(error);
|
|
|
|
|
}
|
2022-11-06 10:17:14 +01:00
|
|
|
}
|
2022-11-06 11:44:43 +01:00
|
|
|
|
|
|
|
|
exports = module.exports = ProgressStream;
|