Open In App

EventEmitter Object in Node.js

Last Updated : 29 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We all know NodeJs applications are run in the single-thread event-driven model. However, NodeJs executes a threads pool in the background of the application, while applications don’t support multi-threads.

This is all possible by using the event model in NodeJs. In this article, we will see the EventEmitter object and how it creates the event and fires the event. But you must need to know what the event is.

Event handling is quite similar to the callback function, but the callback function is used when asynchronous functions return their result and event handling works on the observer pattern. In NodeJs the functions that listeners the events are called observers. When an event occurs listeners’ functions start their execution. There are multiple in-built events available in NodeJs like EventEmitter class. We will show how we can use EventEmitter class in event handling. 

EventEmitter is an in-built event available in NodeJs. Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called “emitters”) emit named events that cause Function objects (“listeners”) to be called” EventEmitter help event emitters to fire events and listeners to act on these events in a simple manner. 

Creating EventEmitter object: We can use EventEmitter by creating its object and then using it for fire events. We will syntax for EventEmitter object creation. Before creating the EventEmitter object you should import the event.

Step 1: Import events module.

var events = require('events');

Step 2: Creates an EventEmitter object.

var eventEmitter = new events.EventEmitter();

Step 3: Then bind the event and event handler together

eventEmitter.on('eventName', eventHandler);

Step 4: We can fire the event by using emit method

eventEmitter.emit('eventName');

Example 1: In this example, we show how to create an EventEmitter object and then fire an event by using emit() method, and bind the connection used on() of EventEmitter. When execution is stopped we fire connections by using emit().

index.js

Javascript




// Import events module
const events = require('events');
 
// Create an eventEmitter object
let eventEmitter = new events.EventEmitter()
// Create an event handler as follows
let connectHandler = function connected() {
    console.log('connection successful.');
    // Fire the data_received event
    eventEmitter.emit('data_received');
}
 
// 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 successfully.');
});
 
// Fire the connection event
eventEmitter.emit('connection');
console.log("Program Ended.");


Step to run the application: Run the below command to execute script.js

node script.js

Output:

Example of EventEmitter object 

Extending EventEmitter class: The EventEmitter class supports inheritance. Sometimes you need to implement a subclass of EventEmitter.

Example 2: In this example, MyEmitter inherits the EventEmitter class. MyEmitter uses the on() method to listen to events. This event is fire using emit().

index.js

Javascript




const EventEmitter = require('events');
 
class MyEmitter extends EventEmitter {
    foo() {
        this.emit('test');
    }
}
 
let myEmitter = new MyEmitter();
myEmitter.on('test', () => console.log('Yay, it works!'));
myEmitter.foo();


Output:

Example of Extending EventEmitter class 

Features of EventEmitter class:

  • This class is for handling events.
  • It can inherit event functionality in other classes.
  • It emits events.
  • It listens to and handles events.
  • It helps to run multiple threads in the background.

EventEmitter Methods:

  • emitobj.on(event, listener)
  • emitobj.emit(event,[arg1],[arg2],..[argN])
  • emitobj.once(event, listener)
  • emitobj.removeListener(event, listener)

Implementation of EventEmitter Methods:

Example: In this example, we see the practical implementation of EventEmitter Methods. We see all four methods like on(), emit(), once(), and removeListener() of EventEmitter.

Javascript




const events = require('events');
const eventEmitter = new events.EventEmitter();
 
// listener #1
let listener1 = function listener1() {
    console.log('listener1 executed.');
}
 
// listener #2
let listener2 = function listener2() {
    console.log('listener2 executed.');
}
 
// Bind the connection event with the listener1 function
eventEmitter.addListener('connection', listener1);
 
// Bind the connection event with the listener2 function
eventEmitter.on('connection', listener2);
 
let eventListeners = require('events').EventEmitter.listenerCount
    (eventEmitter, 'connection');
console.log(eventListeners + " Listener(s) listening to connection event");
 
// Fire the connection event
eventEmitter.emit('connection');
 
// Remove the binding of listener1 function
eventEmitter.removeListener('connection', listener1);
console.log("Listener1 will not listen now.");
 
// Fire the connection event
eventEmitter.emit('connection');
eventListeners = require('events').EventEmitter.listenerCount
    (eventEmitter, 'connection');
 
console.log(eventListeners + " Listener(s) listening to connection event");
console.log("Program Ended.");


Output:

EventEmitter Methods 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads