index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.RegexParser = void 0;
  4. const stream_1 = require("stream");
  5. /**
  6. * A transform stream that uses a regular expression to split the incoming text upon.
  7. *
  8. * To use the `Regex` parser provide a regular expression to split the incoming text upon. Data is emitted as string controllable by the `encoding` option (defaults to `utf8`).
  9. */
  10. class RegexParser extends stream_1.Transform {
  11. regex;
  12. data;
  13. constructor({ regex, ...options }) {
  14. const opts = {
  15. encoding: 'utf8',
  16. ...options,
  17. };
  18. if (regex === undefined) {
  19. throw new TypeError('"options.regex" must be a regular expression pattern or object');
  20. }
  21. if (!(regex instanceof RegExp)) {
  22. regex = new RegExp(regex.toString());
  23. }
  24. super(opts);
  25. this.regex = regex;
  26. this.data = '';
  27. }
  28. _transform(chunk, encoding, cb) {
  29. const data = this.data + chunk;
  30. const parts = data.split(this.regex);
  31. this.data = parts.pop() || '';
  32. parts.forEach(part => {
  33. this.push(part);
  34. });
  35. cb();
  36. }
  37. _flush(cb) {
  38. this.push(this.data);
  39. this.data = '';
  40. cb();
  41. }
  42. }
  43. exports.RegexParser = RegexParser;