Node.js EventEmitter: A Complete Guide

An event-driven design forms the foundation of the Node.js API. Among its features is the events module, which allows for the creation and management of unique events. The EventEmitter class is found in the event module. Named events that invoke the listener functions are released by the EventEmitter object. An essential component of the Node.js ecosystem are the EventEmitters. A net is one of the many items in Node that emit events. Every time a peer connects to it or a connection is closed, the server object sends out an event. When the file is opened, closed, or a read/write action is carried out, the fs.readStream object generates an event. An instance of an event is any object that emits events. EventEmitter.

Since the EventEmitter class is defined in the events module, it must be included in the code with the require statement.

var events = require('events');

To emit an event, an object of the EventEmitter class should be declared.

var eventEmitter = new events.EventEmitter();

An ‘error’ event is emitted by an EventEmitter instance when it detects an error. The ‘newListener’ event is triggered upon adding a new listener, and the’removeListener’ event is triggered upon removing a listener.

Events

  1. newListener(event, listener)
    • event: String – The event name
    • listener: Function – The event handler function
    • This event is emitted any time a listener is added. When triggered, the listener may not yet be added to the array of listeners for the event.
  2. removeListener(event, listener)
    • event: String – The event name
    • listener: Function – The event handler function
    • This event is emitted any time a listener is removed. When triggered, the listener may not yet be removed from the array of listeners for the event.

Instance Methods

  1. addListener(event, listener)
    Adds a listener at the end of the listeners array for the specified event. Returns emitter, so calls can be chained.
  2. on(event, listener)
    Adds a listener at the end of the listeners array for the specified event. Same as addListener.
  3. once(event, listener)
    Adds a one-time listener to the event. This listener is invoked only the next time the event is fired, after which it is removed.
  4. removeListener(event, listener)
    Removes a listener from the listener array for the specified event. If any single listener has been added multiple times, removeListener must be called multiple times to remove each instance.
  5. removeAllListeners([event])
    Removes all listeners, or those of the specified event.
  6. setMaxListeners(n)
    By default, EventEmitters print a warning if more than 10 listeners are added for an event. Set to zero for unlimited.
  7. listeners(event)
    Returns an array of listeners for the specified event.
  8. emit(event, [arg1], [arg2], […])
    Executes each of the listeners in order with the supplied arguments. Returns true if the event had listeners, false otherwise.
  9. off(event, listener)
    Alias for removeListener.

Example

var events = require('events');
var eventEmitter = new events.EventEmitter();

// Listener #1
var listener1 = function listener1() {
   console.log('listener1 executed.');
}

// Listener #2
var 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);

// Fire the connection event
eventEmitter.emit('connection');

When the connection event is fired, the console shows:

listener1 executed.
listener2 executed.

Now, removing listener1 from the connection event and firing the event again:

// Remove listener1 function
eventEmitter.removeListener('connection', listener1);
console.log("Listener1 will not listen now.");

// Fire the connection event again
eventEmitter.emit('connection');

Console output:

listener1 executed.
listener2 executed.
Listener1 will not listen now.
listener2 executed.

Counting Listeners

The EventEmitter class also has a listenerCount() method that returns the number of listeners for a given event.

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

// Listener #1
var listener1 = function listener1() {
   console.log('listener1 executed.');
}

// Listener #2
var listener2 = function listener2() {
  console.log('listener2 executed.');
}

// Bind listeners to the connection event
myEmitter.addListener('connection', listener1);
myEmitter.on('connection', listener2);

// Fire the connection event
myEmitter.emit('connection');
console.log("Number of Listeners:" + myEmitter.listenerCount('connection'));

Output:

listener1 executed.
listener2 executed.
Number of Listeners:2

It might be helpful:

Getting Started with Node.js: Your First Application

What’s New in Node.js 21/22? 

Best Practices for API Design in Full-Stack Development

₹25,000.00

SAP SD S4 HANA

SAP SD (Sales and Distribution) is a module in the SAP ERP (Enterprise Resource Planning) system that handles all aspects of sales and distribution processes. S4 HANA is the latest version of SAP’s ERP suite, built on the SAP HANA in-memory database platform. It provides real-time data processing capabilities, improved…
₹25,000.00

SAP HR HCM

SAP Human Capital Management (SAP HCM)  is an important module in SAP. It is also known as SAP Human Resource Management System (SAP HRMS) or SAP Human Resource (HR). SAP HR software allows you to automate record-keeping processes. It is an ideal framework for the HR department to take advantage…
₹25,000.00

Salesforce Administrator Training

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
₹25,000.00

Salesforce Developer Training

Salesforce Developer Training Overview Salesforce Developer training advances your skills and knowledge in building custom applications on the Salesforce platform using the programming capabilities of Apex code and the Visualforce UI framework. It covers all the fundamentals of application development through real-time projects and utilizes cases to help you clear…
₹25,000.00

SAP EWM

SAP EWM stands for Extended Warehouse Management. It is a best-of-breed WMS Warehouse Management System product offered by SAP. It was first released in 2007 as a part of SAP SCM meaning Supply Chain Management suite, but in subsequent releases, it was offered as a stand-alone product. The latest version…
₹25,000.00

Oracle PL-SQL Training Program

Oracle PL-SQL is actually the number one database. The demand in market is growing equally with the value of the database. It has become necessary for the Oracle PL-SQL certification to get the right job. eLearning Solutions is one of the renowned institutes for Oracle PL-SQL in Pune. We believe…
₹25,000.00

Pega Training Courses in Pune- Get Certified Now

Course details for Pega Training in Pune Elearning solution is the best PEGA training institute in Pune. PEGA is one of the Business Process Management tool (BPM), its development is based on Java and OOP concepts. The PAGA technology is mainly used to improve business purposes and cost reduction. PEGA…
₹27,000.00

SAP PP (Production Planning) Training Institute

SAP PP Training Institute in Pune SAP PP training (Production Planning) is one of the largest functional modules in SAP. This module mainly deals with the production process like capacity planning, Master production scheduling, Material requirement planning shop floor, etc. The PP module of SAP takes care of the Master…
X
WhatsApp WhatsApp us
Call Now Button