【问题标题】:What's the difference between write() and push() for PassThrough streams?PassThrough 流的 write() 和 push() 有什么区别?
【发布时间】:2013-08-08 09:49:24
【问题描述】:

假设我正在使用节点的 PassThrough stream 来测试我的流实用程序,并且我希望从我的流中输出一些数据。

var s = new require('stream').PassThrough();

s.push(x);  // <==== Are these identical?
s.write(x);

有什么理由比另一个更喜欢一个吗?

【问题讨论】:

    标签: node.js testing stream


    【解决方案1】:

    ,它们不相同。

    push 用于实现可读流。它将数据推送到读取队列中,然后可以通过调用 read() 读取该队列。如果用 null 调用它,那么它将发出数据结束 (EOF) 的信号。请参阅给出的注释:

    注意:该函数应该由 Readable 实现者调用,而不是由 Readable 流的消费者调用。

    要实现流,某些方法必须由开发人员编写,给定here

    Use-case                                       Class       Method(s) to implement
    Reading only                                   Readable    _read
    Writing only                                   Writable    _write
    Reading and writing                            Duplex      _read, _write
    Operate on written data, then read the result  Transform   _transform, _flush
    

    push 只能用于支持 read() 的流,即 ReadableDuplexTransform 流。它只能在这些函数 _read、_transform 或 _flush 中使用。 PassThrough 是 Transform 的一种实现。


    write 应该由可写流的用户使用。

    此方法将一些数据写入底层系统,并调用 数据处理完毕后提供回调。

    如果您打算使用 Writable 流(写入其中),请使用 write。 push 不是 write 的替代方案。将 write 用于 PassThrough。

    【讨论】:

    • 感谢您的详尽解释。我认为在测试中模拟流行为有点像实现流,这让我感到困惑。仅从_read_transform_flush 调用push 是非常明确的。了解为什么push 不是_push
    • push 不仅用于流中,还用于低级别对象,如数组和队列(基于数组)。所以也许他们使用的是相同的或者已经修改了它。这取决于他们在内部使用的缓冲区。
    • 仅供参考,节点流文档“流实现者 API”的链接已更改(实现者 => 实现者,AmEng 与 BrEng)。正确的是here
    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2014-03-07
    • 2012-09-09
    • 2013-11-14
    • 2018-12-13
    • 2011-02-14
    相关资源
    最近更新 更多