ProgressCallbackTransform.js 2.0 KB

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