Node.JS Event Mechanism

As mentioned earlier, node.js applications are single threaded. A questions arises here that how come node.js implements concurrency in single threaded. The answer lies in events and callbacks. In this article we shall study node.js event mechanism. An event occurs in response to a specific action or completion of task. For instance when a user clicks on a button an event is fired, similarly when file reading is complete an event is fired etc. The events corresponding to the actions are kept in an event loop. As soon as a task which can fire an event completes, events are fired via callback mechanism. These events are handled by corresponding event handlers.

Actually the speed and concurrency with which a node.js application executes owe itself to these events. As soon as you start a node.js application it declares its variables, initializes the functions and start executing its normal flow, in parallel it generates an event loop which keeps checking if an event has fired.

Event Generation and Handling

There are four steps involved in event generation and handling life cycle. They have been enlisted below.

  • Import “events” module
  • Create an eventEmitter object via events module.
  • Bind the event with the event handler via this eventEmitter “on” method
  • Finally fire an event which will be handled by the event handler.

Node.js Event Mechanism Example

Let’s have a look at a simple example of event generation and handling in node.js

var event = require('events');

var eE = new event.EventEmitter();

var conHandler = function connected() {
   console.log('connection creation passed.');
  
   eE.emit('data_complete');
}

eE.on('connection', conHandler);
 
eE.on('data_complete', function(){
   console.log('data received succesfully.');
});

eE.emit('connection');

console.log("Program execution completed.");

Download the code Try the code

In the above code we first import events module and stored the resulted events object in event variable. Using this event variable we create eventEmitter object eE. We then created an event Handler “conHandler” which first displays the message about connection successful and then fires another event i.e “data_complete”. Next, we use eventEmitter objects on function to bind connection event with conHandler and “data_complete” event with anonymous function. Finally we fire “connection” event via eventEmitter’s “emit” function. This executes the “conHandler” function which displays a message and then fires “data_complete” event which executes he anonymous function that displays message about successful data received.

<<< Node.JS Callback MechanismNode.JS Event Emitter >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .