Table of contents
1.
Introduction
2.
Understanding EventEmitter in Node.js
3.
Key Concepts of EventEmitter
4.
Initialising Node.js event emitter
5.
Passing arguments to the event handler in Node.js Event emitter
6.
Passing multiple arguments in Node.js Event emitter
7.
Methods for EvenEmitter
8.
Best Practices for Using EventEmitter in Node.js
9.
Frequently Asked Questions
9.1.
What is the Node.js Event Emitter?
9.2.
What is the use of EventEmitter in Node.js?
9.3.
What is the Event Loop and Event Emitter in Node.js?
9.4.
Is an Event Emitter Synchronous or Asynchronous?
10.
Conclusion
Last Updated: Oct 20, 2024
Easy

The Node.js Event emitter

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Node.js, an Event Emitter is a core concept that is pivotal in handling asynchronous events and building efficient, event-driven applications. The EventEmitter class, part of the events module, allows objects to emit, listen for, and respond to events, making it a foundational tool for managing communication between different parts of your application. Using event-driven architecture, developers can create highly scalable and responsive systems, as functions are triggered when specific events occur. This blog will explore how the Event Emitter works.

Event Emitter in Nodejs

Understanding EventEmitter in Node.js

EventEmitter in Node.js is a core module that facilitates event-driven programming. It allows objects to emit named events that cause functions (listeners) to be called. EventEmitter is the backbone of Node's asynchronous event-driven architecture, enabling communication between different parts of an application through a publisher-subscriber pattern.

Key Concepts of EventEmitter

Key Concepts of EventEmitter:

  • Events: Named signals emitted by objects
  • Emitters: Objects that emit named events
  • Listeners: Functions that are executed when a specific event is emitted
  • on() / addListener(): Methods to attach a listener to an event
  • emit(): Method to trigger an event
  • removeListener(): Removes a specific listener from an event
  • removeAllListeners(): Removes all listeners from a specific event
  • once(): Adds a one-time listener that automatically removes itself after execution
  • EventEmitter.defaultMaxListeners: Sets the default maximum number of listeners for all emitters
  • newListener event: Fired when a new listener is added
  • removeListener event: Fired when a listener is removed
  • Error event: Special event for error handling

Initialising Node.js event emitter

To initialize the Node.js event emitter, we first have to include the 'events' module. 

// Import events module
const NodeJSEventEmitter = require('events');

// Create an eventEmitter object
const JSEventEmitter = new NodeJSEventEmitter ();

 

This object has many methods. On and emit are two important methods.

  • emit - This method is used to trigger an event
  • on - This method is used to add a callback function that will be executed when the event is triggered.

 

Now let's try creating a start event and react to that by logging into the console:

 

JSEventEmitter.on('start', () => {
 console.log('Start event started');
});

 

The event handler function is triggered when we run the following code and get the console log output.

 

JSEventEmitter.emit('start');

 

Output

Passing arguments to the event handler in Node.js Event emitter

We can pass additional arguments to the event handler. We can do this by passing them as additional arguments to the emit function.

Here is the code for that:

 

JSEventEmitter.on('start', number => {
 console.log(`Start event started ${number}`);
});

// Passing another parameter 777 here
JSEventEmitter.emit('start',777);

 

 

Output

Passing multiple arguments in Node.js Event emitter

We can also pass multiple arguments to the event handler.

JSEventEmitter.on('start', (start, end) => {
 console.log(`started from ${start} to ${end}`);
})

// Passing multiple parameters 777 and 888
JSEventEmitter.emit('start',777,888);

 

Output

Methods for EvenEmitter

The EventEmitter object also exposes several other methods to interact with events, like

MethodDescription
addListener(event, listener)This adds a listener at the end of the listener's array for the specified event. There is no checking done to see if the listener was already added or not.
on(event, listener)This adds a listener at the end of the listener's array for the specified event. There is no checking done to see if the listener was already added or not.
once(event, listener)This adds a one-time listener to the event. The listener is invoked only the next time the event is fired, after which it is removed. 
emit(event, [arg1], [arg2], [...])Emit executes each of the listeners in order with the supplied arguments. If the event had listeners, then it returns true otherwise, false is returned.
listeners(event)This returns an array of listeners for the specified event.
removeListener(event, listener)This removes a listener from the listener array for the specified event. Note that it will change the array indices in the listener array behind the listener. It can remove at most one instance of a listener from the listener array. 
removeAllListeners([event])This removes all the listeners or those of the specified event. 
setMaxListeners(n)If more than 10 listeners are added for a particular event, then, by default, EventEmitter will print a warning. This is a useful default that helps find memory leaks. setMaxListeners() allows us to increase that limit.

Best Practices for Using EventEmitter in Node.js

Here are some best practices for using EventEmitter in Node.js:

  1. Limit the Number of Listeners
    Avoid adding too many listeners to a single event, as this can lead to memory leaks. You can use emitter.setMaxListeners(n) to adjust the default limit if needed.
  2. Handle Errors Gracefully
    Always handle the 'error' event. If an error event is emitted without a corresponding listener, it will cause your program to crash.
  3. Use Descriptive Event Names
    Choose meaningful and descriptive event names to make your code easier to understand and maintain.
  4. Remove Unused Listeners
    To avoid memory leaks, always remove listeners when they are no longer needed using emitter.removeListener() or emitter.off() in modern Node.js versions.
  5. Avoid Long Synchronous Listeners
    Keep event listener functions short and avoid blocking operations. Use asynchronous functions to prevent the event loop from being blocked.
  6. Leverage once() for One-Time Events
    If an event should only trigger once, use emitter.once() to automatically remove the listener after the first execution.
  7. Document Custom Events
    Clearly document any custom events you emit, making it easier for other developers (or yourself) to understand the code later.

Frequently Asked Questions

What is the Node.js Event Emitter?

The Node.js Event Emitter is a core module that allows objects to emit named events and register listeners to respond to those events. It is an essential part of building event-driven applications, enabling efficient communication between different components of a system.

What is the use of EventEmitter in Node.js?

The EventEmitter in Node.js is used to create custom events and attach listeners to them. It allows developers to emit events and react to those events efficiently, supporting asynchronous task handling and promoting an event-driven architecture in applications.

What is the Event Loop and Event Emitter in Node.js?

The Event Loop is a mechanism in Node.js that handles asynchronous operations, ensuring non-blocking execution of code. The EventEmitter works within this event-driven system, emitting and handling events, and enabling the execution of asynchronous functions through event listeners.

Is an Event Emitter Synchronous or Asynchronous?

Event Emitters in Node.js are primarily synchronous, meaning that listeners are called immediately when an event is emitted. However, the listener functions can perform asynchronous operations, using callbacks, promises, or async/await to manage non-blocking tasks.

Conclusion

The Node.js event emitter is part of the events module. It offers a way to handle our events. A lot of interactions coming from the user are handled by events. Interactions can be clicking the button, pressing buttons on the keyboard, etc. Node.js event emitter gives a  way to service these events.

Live masterclass