index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ReadyParser = void 0;
  4. const stream_1 = require("stream");
  5. /**
  6. * A transform stream that waits for a sequence of "ready" bytes before emitting a ready event and emitting data events
  7. *
  8. * To use the `Ready` parser provide a byte start sequence. After the bytes have been received a ready event is fired and data events are passed through.
  9. */
  10. class ReadyParser extends stream_1.Transform {
  11. delimiter;
  12. readOffset;
  13. ready;
  14. constructor({ delimiter, ...options }) {
  15. if (delimiter === undefined) {
  16. throw new TypeError('"delimiter" is not a bufferable object');
  17. }
  18. if (delimiter.length === 0) {
  19. throw new TypeError('"delimiter" has a 0 or undefined length');
  20. }
  21. super(options);
  22. this.delimiter = Buffer.from(delimiter);
  23. this.readOffset = 0;
  24. this.ready = false;
  25. }
  26. _transform(chunk, encoding, cb) {
  27. if (this.ready) {
  28. this.push(chunk);
  29. return cb();
  30. }
  31. const delimiter = this.delimiter;
  32. let chunkOffset = 0;
  33. while (this.readOffset < delimiter.length && chunkOffset < chunk.length) {
  34. if (delimiter[this.readOffset] === chunk[chunkOffset]) {
  35. this.readOffset++;
  36. }
  37. else {
  38. this.readOffset = 0;
  39. }
  40. chunkOffset++;
  41. }
  42. if (this.readOffset === delimiter.length) {
  43. this.ready = true;
  44. this.emit('ready');
  45. const chunkRest = chunk.slice(chunkOffset);
  46. if (chunkRest.length > 0) {
  47. this.push(chunkRest);
  48. }
  49. }
  50. cb();
  51. }
  52. }
  53. exports.ReadyParser = ReadyParser;