Files
cloudron-box/src/progress-stream.js
2024-05-31 16:55:41 +02:00

50 lines
1.3 KiB
JavaScript

'use strict';
const stream = require('stream'),
TransformStream = stream.Transform;
class ProgressStream extends TransformStream {
constructor(options) {
super();
this._options = Object.assign({ interval: 10 * 1000 }, options);
this._transferred = 0;
this._delta = 0;
this._started = false;
this._startTime = null;
this._interval = null;
}
stats() {
const totalSecs = Math.round((Date.now() - this._startTime)/1000);
return { startTime: this._startTime, totalSecs, transferred: this._transferred };
}
_start() {
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);
}
_stop() {
clearInterval(this._interval);
}
_transform(chunk, encoding, callback) {
if (!this._started) this._start();
this._transferred += chunk.length;
this._delta += chunk.length;
callback(null, chunk);
}
_flush(callback) {
this._stop();
callback(null);
}
}
exports = module.exports = ProgressStream;