Event Emitter

Nodejs follow Event-Driven based architecture so every action is an event in Nodejs like open the file to read is an event.

In Nodejs to use Event Emitter firstly include event module in the code.


var events = require('events');

after that create the object through new keyword.


var eventEmitter = new events.EventEmitter();

to assign the custom event we use “on” keyword

//Create an custom event handler:


var customEventHandler =  ()=> {

   console.log('an event occurred!');
}

eventEmitter.on('customEventName', customEventHandler);

fire the event through emit() method.


eventEmitter.emit('customEventName');

We want to alert everyone when a new user joins the chat room. We’ll need an event listener for a userJoined event. First, we’ll write a function that will act as our event listener, then we can use EventEmitters on the method to set the listener.


const events = require('events');
const chatRoomEvents = new events.EventEmitter;

function userJoined(username){
  // Assuming we already have a function to alert all users.
  alertAllUsers('User ' + username + ' has joined the chat.');
}

// Run the userJoined function when a 'userJoined' event is triggered.
chatRoomEvents.on('userJoined', userJoined);

The next step would be to make sure that our chat room triggers a userJoined event whenever someone logs in so that our event handler is called. EventEmitter has an emit method that we use to trigger the event. We would want to trigger this event from within a login function inside of our chatroom module.


function login(username){
  chatRoomEvents.emit('userJoined', username);
}

there are lots of default events in Nodejs but I am showing some events.


newListener('eventName',listener)

It is called when we want to add listner in the event.


removeListener('eventName',listener);

It is called when we want to remove listner from the event.


once('eventName', listener)

Adds a one-time listener function for the event named eventName