Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between write() and push() for PassThrough streams?

Say I'm using node's PassThrough stream to test my stream utility and I want some data to come out of my stream.

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

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

Any reason to prefer one over the other?

like image 468
hurrymaplelad Avatar asked Aug 07 '13 06:08

hurrymaplelad


1 Answers

No, they are not identical.

push is for implementing a readable stream. It pushes data into the read queue, which can then be read by calling read(). If it is called with null then it will signal the end of the data (EOF). See the Note given :

Note: This function should be called by Readable implementors, NOT by consumers of Readable streams.

To implement a stream, certain methods must be written by the developer, given 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 must only be used for streams capable of read() i.e. Readable, Duplex and Transform streams. It must only be used inside these functions _read, _transform or _flush. PassThrough is an implementation of Transform.


write is supposed to be used by the user of a writable stream.

This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.

If you intend to use a Writable stream (write into it) then use write. push is not an alternative for write. Use write for PassThrough.

like image 183
user568109 Avatar answered Nov 15 '22 07:11

user568109