Filtering Stream object in node.js

后端 未结 2 1398
情话喂你
情话喂你 2021-01-05 14:34

It seems to me that an elegant way to process certain kinds of data in Node.js would be to chain processing objects, like UNIX pipes.

For example, grep:



        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 14:53

    Although the answer that exists is nice, it still requires a bit of digging around on behalf of those looking for answers.

    The following code completes the example the OP gave, using the Node 0.10 stream API.

    var stream = require('stream')
    var util = require('util')
    
    function Grep(pattern) {
      stream.Transform.call(this)
    
      this.pattern = pattern
    }
    
    util.inherits(Grep, stream.Transform)
    
    Grep.prototype._transform = function(chunk, encoding, callback) {
      var string = chunk.toString()
    
      if (string.match(this.pattern)) {
        this.push(chunk)
      }
    
      callback()
    }
    
    var grep = new Grep(/foo/)
    process.stdin.pipe(grep)
    grep.pipe(process.stdout)
    

提交回复
热议问题