index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ByteLengthParser = void 0;
  4. const stream_1 = require("stream");
  5. /**
  6. * Emit data every number of bytes
  7. *
  8. * A transform stream that emits data as a buffer after a specific number of bytes are received. Runs in O(n) time.
  9. */
  10. class ByteLengthParser extends stream_1.Transform {
  11. length;
  12. position;
  13. buffer;
  14. constructor(options) {
  15. super(options);
  16. if (typeof options.length !== 'number') {
  17. throw new TypeError('"length" is not a number');
  18. }
  19. if (options.length < 1) {
  20. throw new TypeError('"length" is not greater than 0');
  21. }
  22. this.length = options.length;
  23. this.position = 0;
  24. this.buffer = Buffer.alloc(this.length);
  25. }
  26. _transform(chunk, _encoding, cb) {
  27. let cursor = 0;
  28. while (cursor < chunk.length) {
  29. this.buffer[this.position] = chunk[cursor];
  30. cursor++;
  31. this.position++;
  32. if (this.position === this.length) {
  33. this.push(this.buffer);
  34. this.buffer = Buffer.alloc(this.length);
  35. this.position = 0;
  36. }
  37. }
  38. cb();
  39. }
  40. _flush(cb) {
  41. this.push(this.buffer.slice(0, this.position));
  42. this.buffer = Buffer.alloc(this.length);
  43. cb();
  44. }
  45. }
  46. exports.ByteLengthParser = ByteLengthParser;