【发布时间】:2013-08-08 09:49:24
【问题描述】:
假设我正在使用节点的 PassThrough stream 来测试我的流实用程序,并且我希望从我的流中输出一些数据。
var s = new require('stream').PassThrough();
s.push(x); // <==== Are these identical?
s.write(x);
有什么理由比另一个更喜欢一个吗?
【问题讨论】:
假设我正在使用节点的 PassThrough stream 来测试我的流实用程序,并且我希望从我的流中输出一些数据。
var s = new require('stream').PassThrough();
s.push(x); // <==== Are these identical?
s.write(x);
有什么理由比另一个更喜欢一个吗?
【问题讨论】:
不,它们不相同。
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() 的流,即 Readable、Duplex 和 Transform 流。它只能在这些函数 _read、_transform 或 _flush 中使用。 PassThrough 是 Transform 的一种实现。
write 应该由可写流的用户使用。
此方法将一些数据写入底层系统,并调用 数据处理完毕后提供回调。
如果您打算使用 Writable 流(写入其中),请使用 write。 push 不是 write 的替代方案。将 write 用于 PassThrough。
【讨论】:
_read、_transform 或_flush 调用push 是非常明确的。了解为什么push 不是_push?