Reputation: 47
I'm assuming that Node.js continuously listens for events and handles the listener code asynchronously whenever an event is fired.
I have tried defining a custom event using the 'events' module, that is manually emitted in the script.
var events = require('events');
var myEmitter = new events.EventEmitter();
myEmitter.on('someEvent', function(msg){
console.log(msg);
});
myEmitter.emit('someEvent', 'the event is emitted');
When I run the above script, the process terminates after handling the event only once. How does Node.js know that there won't be more events that can be triggered in the future? I've seen that 'http' module's server.listen() listens for incoming connections continuously and doesn't terminate after getting the first connection. Why doesn't my code behave in the same way?
Or in other words, How can I define events that are asynchronous and listened continuously?
EDIT: I would also like to know how the events that occur unpredictably (eg. Browser button clicks, server getting a connection etc.) work under the hood, such that the program runs continuously without terminating.
Upvotes: 3
Views: 1243
Reputation: 23495
We are talking about two different things here. Events and Sockets.
In your case, you are saying to node that when the event named someEvent
appears, you want to handle it. And then you are emitting this event. When you do, node.js sees there is a custom handler for it and calls your function. When your function ends, there are no more things to do in the program and it terminates.
Node.js does not actively wait for events like :
while (1) {
if (isThereANewEvent()) treatTheNewEvent();
}
It's a passive wait.
On the other hand, sockets are I/O and when you are starting a server, it has an active wait. That's why your program won't terminate after calling .listen
Upvotes: 1