45 lines
1.1 KiB
JavaScript
45 lines
1.1 KiB
JavaScript
'use strict';
|
|
|
|
exports = module.exports = ProgressStream;
|
|
|
|
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;
|
|
}
|
|
|
|
_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);
|
|
}
|
|
}
|