Search This Blog


Node.js - Event Loop and Event Emitter

Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast compared to other similar technologies. As soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for event to occur.

Node.js has multiple in-built events available through events module and EventEmitter class which is used to bind events.

EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.

Below is an example :

Step 1: Run "npm init"

Step 2 : Insert all required parameter in 'npm init' and create the start page 'index.js'.
Step 3: index.js will be as below

// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
// Create an event handler as follows
var connectHandler = function connected() {
   console.log('connection succesful.');
   // Fire the data_received event
// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);

// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function(){
   console.log('data received succesfully.');
// Fire the connection event
var eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'data_received');
console.log(eventListeners + " Listner(s) listening to data_received event");
console.log("Listner Count Ended...............");
console.log("Connection Event Ended...............");
console.log("data_received Event Ended...............");
console.log("Program Ended...............");
Step 5: Run the application by 'node index.js' and see the responses in console.


No comments: