ProgressCallbackTransform.js 1.8 KB

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