过滤node.js中的Stream对象 [英] Filtering Stream object in node.js

查看:116
本文介绍了过滤node.js中的Stream对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,在Node.js中处理某些类型数据的优雅方法是链接处理对象,如UNIX管道。

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.

例如, grep:

function Grep(pattern) {
    ...
}
util.inherits(Grep, stream.Stream);

Grep.prototype.???? = ???????  // What goes here?

grep = new Grep(/foo/);

process.stdin.pipe(grep);
myStream.pipe(process.stdout);

然而,我并不清楚如何为了这个需要覆盖各种Stream方法工作。

However it's not at all clear to me how the various Stream methods need to be overridden in order for this to work.

如何创建一个简单地从输入复制到输出的Stream对象?据推测,更复杂的过滤流变得微不足道。

How can I create a Stream object that simply copies from its input to its output? Presumably with that answered, more sophisticated filtering streams become trivial.

更新:感觉好像以下应该有效(用CoffeeScript表示,所以我没有用JS语法填充此框!):

Update: it feels as if the following should work (expressed in CoffeeScript, so I don't fill this box with JS syntax!):

class Forwarder extends stream.Stream
    write: (chunk, encoding) ->
        @emit 'data', chunk
    end: (chunk, encoding) =>
        if chunk?
            @emit 'data', chunk
        @emit 'end'

fwd = new Forwarder()
fwd.pipe(process.stdout);
process.stdin.pipe(fwd);
process.stdin.resume();

然而,在此脚本中捕获内容不会输出任何内容。在脚本中显式调用'fwd.write()'会导致stdout输出。

However catting something to this script doesn't output anything. Calling 'fwd.write()' explicitly in the script does cause output on stdout.

推荐答案

你非常接近。

因为您使用的是非常低级的流类,所以需要设置流可写属性以使其成为可写流。如果您正在从流中读取,则需要设置可读属性。此结束事件也没有任何参数。

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



更新



以上答案适用于节点中的V1流<= 0.8。如果你使用> 0.8,Node已经添加了更多旨在扩展的特定类,所以你会使用更像这样的东西:

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

处理 chunk 并实际推送你的碎片想要。

Processing chunk and pushing the pieces you actually want.

这篇关于过滤node.js中的Stream对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆