代码之家  ›  专栏  ›  技术社区  ›  learner

节点将正则表达式应用于流

  •  0
  • learner  · 技术社区  · 3 年前

    我想将正则表达式应用于我们从输入流中获得的数据,并返回一个响应流。

    以下是我尝试过的:

    const stream = require('stream');
    
    function processStream(is, expression) {
        // I have to write code from here
        is.on("data", (chunk) => {
            expression.test(chunk);
            // how to return the result back
        });
    }
    

    测试此程序的代码:

    const is = stream.Readable.from(['aaa', 'aab']).setEncoding('utf-8');
    
    const os = filterStream(is, /aaa/i);
    
    streamToArray(os).then(consolo.log, console.error);
    

    我想知道如何将正则表达式应用于数据并返回响应。

    对于我的任务,我必须在函数内部编写代码: function processStream(is, expression) { 我必须返回一个流,其中包含与所提供的正则表达式匹配的块。

    1 回复  |  直到 3 年前
        1
  •  1
  •   Heiko Theißen    3 年前

    由于流是以块的形式到达的,因此必须决定如果一个块与正则表达式不匹配,但与下一个块匹配,该怎么办。请注意,您无法控制如何将流切割成块!

    如果您希望不是逐块匹配传入流,而是逐行匹配(您可以控制),并且只输出匹配的行,则可以使用 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();
      }
    }
    

    但结果取决于这些块是如何被切割的。

    推荐文章