假设我正在使用节点的PassThrough 流来测试我的流实用程序,并且我想要一些数据从我的流中出来。
var s = new require('stream').PassThrough();
s.push(x); // <==== Are these identical?
s.write(x);
有什么理由比另一个更喜欢一个吗?
假设我正在使用节点的PassThrough 流来测试我的流实用程序,并且我想要一些数据从我的流中出来。
var s = new require('stream').PassThrough();
s.push(x); // <==== Are these identical?
s.write(x);
有什么理由比另一个更喜欢一个吗?
不,它们不相同。
push用于实现可读流。它将数据推送到读取队列中,然后可以通过调用 read() 读取该队列。如果用 null 调用它,那么它将发出数据结束 (EOF) 的信号。请参阅给出的注释:
注意:这个函数应该由 Readable 实现者调用,而不是由 Readable 流的消费者调用。
要实现流,某些方法必须由开发人员编写,如下所示。
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。