match.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. module.exports = Match;
  3. var Transform = require('stream').Transform;
  4. var inherits = require("util").inherits;
  5. var Buffers = require('buffers');
  6. if (!Transform) {
  7. Transform = require('readable-stream/transform');
  8. }
  9. inherits(Match, Transform);
  10. function Match(opts, matchFn) {
  11. if (!(this instanceof Match)) {
  12. return new Match(opts, matchFn);
  13. }
  14. //todo - better handle opts e.g. pattern.length can't be > highWaterMark
  15. this._opts = opts;
  16. if (typeof this._opts.pattern === "string") {
  17. this._opts.pattern = new Buffer(this._opts.pattern);
  18. }
  19. this._matchFn = matchFn;
  20. this._bufs = Buffers();
  21. Transform.call(this);
  22. }
  23. Match.prototype._transform = function (chunk, encoding, callback) {
  24. var pattern = this._opts.pattern;
  25. this._bufs.push(chunk);
  26. var index = this._bufs.indexOf(pattern);
  27. if (index >= 0) {
  28. processMatches.call(this, index, pattern, callback);
  29. } else {
  30. var buf = this._bufs.splice(0, this._bufs.length - chunk.length);
  31. if (buf && buf.length > 0) {
  32. this._matchFn(buf.toBuffer());
  33. }
  34. callback();
  35. }
  36. };
  37. function processMatches(index, pattern, callback) {
  38. var buf = this._bufs.splice(0, index).toBuffer();
  39. if (this._opts.consume) {
  40. this._bufs.splice(0, pattern.length);
  41. }
  42. this._matchFn(buf, pattern, this._bufs.toBuffer());
  43. index = this._bufs.indexOf(pattern);
  44. if (index > 0 || this._opts.consume && index === 0) {
  45. process.nextTick(processMatches.bind(this, index, pattern, callback));
  46. } else {
  47. callback();
  48. }
  49. }