ng.newbie
ng.newbie

Reputation: 3218

Why does the data event only stop the NodeJS run time from exiting?

Take the following code in nodejs-:

console.log("Hello world");
process.stdin.on('connect', function() {

    });

This prints Hello World and then Node exits. But when I replace the connect event with 'data' event, the Node runtime does not exit.

Why is that ? What is so special about the EventEmitter's data event ? Does it open a socket connection ? So in the on() method is there code like the following -:

function on(event, callback) {
if(event === 'data') {
     //open socket
     //do work
    }
else {
   //do non-socket work
   }
}

Is there a clear answer to why adding a listener to the data event "magically" open a socket.

Upvotes: 0

Views: 227

Answers (2)

ponury-kostek
ponury-kostek

Reputation: 8060

Node.js event loop has couple phases of processing, in your case it's poll phase. Which process for example incoming data (process.stdin.on('data', cb)) so until there is a callback that can handle this event, a this event can occur, node event loop is not empty and node will not exit.

process.stdin is Readable Stream which has fallowing events:

  • close
  • data
  • end
  • error
  • readable

so there is nothing like connect.

process.stdin.on('readable', function() {
    console.log('Readable');
});

Code above will print Readable and exit because after firing event stream is not in flowing state so it will exit event loop because it's empty, but data event sets stream state to flowing, so if stream state is set to flowing and if readableState.reading is true it will prevent node to exit. if you do

process.stdin.on('data', function(data) {
    console.log(data.toString());
});

if you write anything in console when this is running it will work like echo.

https://github.com/nodejs/node/blob/master/lib/_stream_readable.js#L774-L795

You can read full explanation how event loop works here https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

Upvotes: 1

ralphtheninja
ralphtheninja

Reputation: 133008

If we assume index.js contains

process.stdin.on('data', console.log)

and you do node index.js, then the process waits for input on stdin.

If you send some data on stdin via e.g. echo woohoo | node index.js then the buffer will be written and the process exits.

Upvotes: 0

Related Questions