由于流是以块的形式到达的,因此必须决定如果一个块与正则表达式不匹配,但与下一个块匹配,该怎么办。请注意,您无法控制如何将流切割成块!
如果您希望不是逐块匹配传入流,而是逐行匹配(您可以控制),并且只输出匹配的行,则可以使用
readline.createInterface
:
class Matcher extends stream.Transform {
constructor(expression) {
super();
this.is = new stream.PassThrough();
readline.createInterface({input: this.is, crlfDelay: Infinity})
.on("line", function(line) {
var m = line.match(expression);
if (m) this.push(line + "\n");
// or: this.push(m[0]) if you only want the match, not the whole line
}.bind(this));
}
_transform(chunk, encoding, callback) {
this.is.write(chunk);
callback();
}
}
function processStream(is, expression) {
return is.pipe(new Matcher(expression));
}
如果要逐块匹配,则更简单:
class Matcher extends stream.Transform {
constructor(expression) {
super();
this.expression = expression;
}
_transform(chunk, encoding, callback) {
if (chunk.toString(encoding).match(this.expression))
this.push(chunk);
callback();
}
}
但结果取决于这些块是如何被切割的。