index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.InterByteTimeoutParser = void 0;
  4. const stream_1 = require("stream");
  5. /**
  6. * A transform stream that buffers data and emits it after not receiving any bytes for the specified amount of time or hitting a max buffer size.
  7. */
  8. class InterByteTimeoutParser extends stream_1.Transform {
  9. maxBufferSize;
  10. currentPacket;
  11. interval;
  12. intervalID;
  13. constructor({ maxBufferSize = 65536, interval, ...transformOptions }) {
  14. super(transformOptions);
  15. if (!interval) {
  16. throw new TypeError('"interval" is required');
  17. }
  18. if (typeof interval !== 'number' || Number.isNaN(interval)) {
  19. throw new TypeError('"interval" is not a number');
  20. }
  21. if (interval < 1) {
  22. throw new TypeError('"interval" is not greater than 0');
  23. }
  24. if (typeof maxBufferSize !== 'number' || Number.isNaN(maxBufferSize)) {
  25. throw new TypeError('"maxBufferSize" is not a number');
  26. }
  27. if (maxBufferSize < 1) {
  28. throw new TypeError('"maxBufferSize" is not greater than 0');
  29. }
  30. this.maxBufferSize = maxBufferSize;
  31. this.currentPacket = [];
  32. this.interval = interval;
  33. }
  34. _transform(chunk, encoding, cb) {
  35. if (this.intervalID) {
  36. clearTimeout(this.intervalID);
  37. }
  38. for (let offset = 0; offset < chunk.length; offset++) {
  39. this.currentPacket.push(chunk[offset]);
  40. if (this.currentPacket.length >= this.maxBufferSize) {
  41. this.emitPacket();
  42. }
  43. }
  44. this.intervalID = setTimeout(this.emitPacket.bind(this), this.interval);
  45. cb();
  46. }
  47. emitPacket() {
  48. if (this.intervalID) {
  49. clearTimeout(this.intervalID);
  50. }
  51. if (this.currentPacket.length > 0) {
  52. this.push(Buffer.from(this.currentPacket));
  53. }
  54. this.currentPacket = [];
  55. }
  56. _flush(cb) {
  57. this.emitPacket();
  58. cb();
  59. }
  60. }
  61. exports.InterByteTimeoutParser = InterByteTimeoutParser;