What are event emitters in Node.js?

Node.js helps us develop most back-end functionalities of a web application, just like working with JavaScript events on the front-end of a web application.

Events in Node.js

The events module helps us perform the same functions while working with Node.js on the back-end of an application.

The eventEmitter class in Node.js

The eventEmitter class is present in the event module, which aids in managing the events. This gives us room to raise a web event from any end of the application.

A listener can then listen to this web event from any end it is on, as well as carry out some necessary actions.

on() and emit() functions

We have two basic member functions in the eventEmitter module: on() and emit().

  • The on() method helps add a callback function to our event or listen to the created event.

  • The emit() method is used to trigger an event.
    To use eventEmitters, you must ensure that Node.js is pre-installed on your computer.

Syntax

To get started, we initialize the event module.


const EventEmitter = require('events');

Next, we can create an eventEmitter object.


const emitter = new EventEmitter();

In the created event, add a callback with the on() method.


emitter.on('real', function()
{ console.log('TESTING MY NEW EVENT CALL');
});

We now trigger this event with the emit() method.


emitter.emit('real');

At this point, the event has been triggered, and we get our console.log output in our terminal.


const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('real', function()
{ console.log('TESTING MY NEW EVENT CALL');
});
emitter.emit('real');

It is possible to add a one-time listener to an event, but we can only do that with the once(); method.

We can remove an event listener from an event using the removeListener(); method, or remove all listeners with the removeAllisteners(); method.

We can add as many listeners as possible with the on() method and trigger with the emit() method.

Code

Try out the event code below.

const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('real', function()
{ console.log('TESTING MY NEW EVENT CALL');
});
emitter.emit('real');

Free Resources