Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between readable and data event of process.stdin stream?

say I have

process.stdin.setEncoding('utf8'); var myString = ''; 

What are the differences between

process.stdin.on('readable', function() {   myString += process.stdin.read(); }); 

and

process.stdin.on('data', function(chunk) {   myString += chunk; }); 

They give me the same myString if the input string is the same once stdin is end

What are the best practices for each? Thanks

like image 953
stevemao Avatar asked Oct 03 '14 06:10

stevemao


1 Answers

They are two different APIs that allow you to access the same stream of data blocks. The 'readable' API was introduced in Node 0.10.0 as part of "Streams 2", so if you search for that, it should help. The core of the issue is that the 'readable' interface allows for much simpler managing and buffering of data.

The 'data' example calls your function with a chunk, and you have no choice but to handle it, or else it will be lost forever. In the 'readable' example, the function tells you that data is available, but you can read it at any time. This allows the underlying system to know whether or not you have dealt with the data yet so it is very simple to support a concept called backpressure.

For example, in a networked stream, if a client is sending data over a TCP connection to a server and the server is super busy, it will receive readable events, but it could choose to wait to read the data until it actually has the resources to deal with the data. By not reading the data, the stream will buffer it and as that buffer approaches a maximum size, the stream will stop reading packets from the operating system to avoid taking up too much RAM. Then the operating system will start dropping packets, and since the packets were dropped, the client that is sending the data will reduce the speed at which it is sending data to try to make fewer packets drop.

This is all technically supported with the older stream "V1" implementation, but it was much harder to do.

So basically, if you are expecting a ton of data, using 'readable' or designing your streams to be piped is a very good idea, but if you are just reading bits of data from a terminal, then chances are you will see zero difference.

like image 195
loganfsmyth Avatar answered Sep 22 '22 03:09

loganfsmyth