这个代码可能会失去一些匹配吗?

在我的NodeJS学习之旅中,我在一本书(NodeJS in Practice)中find了这个示例代码,它使用stream来查找来自另一个stream的数据中的一些匹配。

var Writable = require('stream').Writable; var util = require('util'); module.exports = CountStream; util.inherits(CountStream, Writable); function CountStream(matchText, options) { Writable.call(this, options); this.count = 0; this.matcher = new RegExp(matchText, 'ig'); } CountStream.prototype._write = function(chunk, encoding, cb) { var matches = chunk.toString().match(this.matcher); if (matches) { this.count += matches.length; } cb(); }; CountStream.prototype.end = function() { this.emit('total', this.count); }; 

而使用stream的代码:

 var CountStream = require('./countstream'); var countStream = new CountStream('book'); var http = require('http'); http.get('http://www.manning.com', function(res) { res.pipe(countStream); }); countStream.on('total', function(count) { console.log('Total matches:', count); }); 

如果一场比赛中有两个数据块被打破,是不是可能会输掉一些比赛?

例如,第一块数据包含“This a bo” ,另一块包含“我的好”。 其中没有人独立书本,但整个数据包含一本书

什么是find所有比赛的最佳解决scheme?

所以,就像我在我的评论中解释的那样,如果你知道正则expression式匹配的string的最大长度(计算最大长度,请参阅https://stackoverflow.com/a/31173778/4114922上的非常好的答案)可以caching先前的块并将其连接到新的块。 用这种方法,我认为你不会失去任何匹配。

 var Writable = require('stream').Writable; var util = require('util'); module.exports = CountStream; util.inherits(CountStream, Writable); function CountStream(matchText, maxPatternLength, options) { Writable.call(this, options); this.count = 0; this.matcher = new RegExp(matchText, 'ig'); this.previousCache = undefined; this.maxPatternLength = maxPatternLength; } CountStream.prototype._write = function(chunk, encoding, cb) { var text; if(this.previousCache === undefined) { text = chunk.toString(); } else { text = this.previousCache + chunk.toString(); } var matches = text.match(this.matcher); if (matches) { this.count += matches.length; } this.previousCache = text.substring(text.length - this.maxPatternLength); cb(); }; CountStream.prototype.end = function() { this.emit('total', this.count); };