javascript - 此代码是否有可能丢失一些匹配项?

标签 javascript node.js

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

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);
};

以及使用流的代码:

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);
});

如果匹配在两个数据 block 中中断,是否有可能丢失一些匹配?

例如第一个数据 block 包含 'This a bo',另一个数据 block 包含 'ok of mine。' 没有人没有 book 独立,但整个数据包含一本书

找到所有匹配项的最佳解决方案是什么?

最佳答案

所以,就像我在评论中解释的那样,如果您知道与您的正则表达式匹配的字符串的最大长度(要计算最大长度,请参阅 https://stackoverflow.com/a/31173778/4114922 的非常好的答案),您可以缓存前一个 block 并连接它到新的 block 。 使用这种方法,我认为您不会输掉任何比赛。

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);
};

关于javascript - 此代码是否有可能丢失一些匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31100065/

相关文章:

node.js - 我无法在 Node 中发出 Web 请求

javascript - 用户在输入中键入时在符号后自动留出空格

javascript - 如何计算 AngularJS 中选中的复选框的数量?

javascript - 获取传递到包含的js文件中的ejs文件的数据

javascript - Heroku 无法运行 Node ES6 代码

javascript - 创建实例时在构造函数中声明变量而不赋值

javascript - 在 React 中扩充对象

javascript - jQuery - 异步 Ajax 请求?

javascript - 如何在 react 表渲染后执行代码?

jquery - Uncaught ReferenceError : io is not defined