Filtering Stream object in node.js

后端 未结 2 1416
情话喂你
情话喂你 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:59

    You are so very close.

    Because you are using the very low-level stream class, you need to set the stream writable property to make it a writable stream. If you were reading from the stream, you'd need to set the readable property. Also the end event doesn't have any arguments.

    class Forwarder extends stream.Stream
      constructor: ->
        @writable = true
      write: (chunk, encoding) ->
        @emit 'data', chunk
      end: ->
        @emit 'end'
    
    fwd = new Forwarder()
    fwd.pipe(process.stdout);
    process.stdin.pipe(fwd);
    process.stdin.resume();
    

    Update

    The answer above applied to V1 streams in Node <= 0.8. If you are using > 0.8, Node has added more specific classes that are designed to be extended, so you would use something more like this:

    class Forwarder extends stream.Transform
        _transform: (chunk, encoding, callback) ->
          this.push(chunk);
          callback();
    

    Processing chunk and pushing the pieces you actually want.

提交回复
热议问题