An event in NodeJS is an action or occurrence, such as a user click, a file being read, or a message being received, that NodeJS can respond to. Events are managed using the EventEmitter class, which is part of NodeJS’s built-in events module. This allows NodeJS to react to various actions asynchronously.
How Do Events Work in NodeJS?
1. Event-Driven Model
- NodeJS uses an event-driven approach, meaning it waits for events (such as a user action or data) to occur and then takes action when those events happen.
2. EventEmitter
- An
EventEmitter
is an object that can generate events in NodeJS. - You can set up “listeners” that wait for these events to happen and then run a function (called a callback) when the event occurs.
3. Event Loop
- The event loop is a mechanism that runs in the background, continuously checking for events.
- When an event occurs, the event loop triggers the callback function that was registered for that event.
EventEmitter Class
At the core of the NodeJS event system is the EventEmitter class. This class allows objects to emit named events that can be listened to by other parts of your application. It is included in the built-in events module.
Key Features of EventEmitter
- on(event, listener): Adds a listener that waits for a specific event to occur.
- emit(event, [arg1, arg2, …]): Triggers an event and calls all the listeners associated with it.
- once(event, listener): Adds a listener that is executed only the first time the event is triggered.
- removeListener(event, listener): Removes a specific listener for an event.
- removeAllListeners(event): Removes all listeners for a particular event.
Working with Events in NodeJS
Step 1: Importing the Events Module
To use events in your application, first import the events module and create an instance of the EventEmitter class.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
Step 2: Registering Event Listeners
You can register listeners for specific events using the on() method. The first argument is the event name, and the second is the callback function that gets executed when the event is emitted.
myEmitter.on('event', () => {
console.log('An event occurred!');
});
Step 3: Emitting Events
To trigger an event, use the emit() method with the event name as the first argument. It will call all the listeners attached to that event.
myEmitter.emit('event'); // Output: An event occurred!
Listening events
Before emitting an event, you must first register listeners (callback functions) that will listen for the event.
Syntax:
eventEmitter.addListener(event, listener)
eventEmitter.on(event, listener)
eventEmitter.once(event, listener)
Removing Listener
To remove a listener for an event, use removeListener() method with the event name and listener function. If you want to remove all listeners for an event, use removeAllListeners().
Syntax:
eventEmitter.removeListener(event, listener)
eventEmitter.removeAllListeners([event])
Note:
- Removing the listener from the array will change the sequence of the listener’s array, hence it must be carefully used.
- The eventEmitter.removeListener() will remove at most one instance of the listener which is in front of the queue.
Now, let us understand with the help of the example:
javascript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
var fun1 = (msg) => {
console.log("Message from fun1: " + msg);
};
var fun2 = (msg) => {
console.log("Message from fun2: " + msg);
};
// Registering fun1 and fun2
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun2);
// Removing listener fun1 that was
// registered on the line 13
eventEmitter.removeListener('myEvent', fun1);
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
// Removing all the listeners to myEvent
eventEmitter.removeAllListeners('myEvent');
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
Output:
Message from fun1: Event occurred
Message from fun2: Event occurred
eventEmitter.listeners()
It returns an array of listeners for the specified event.
Syntax:
eventEmitter.listeners(event)
eventEmitter.listenerCount()
It returns the number of listeners listening to the specified event.
Syntax:
eventEmitter.listenerCount(event)
eventEmitter.prependOnceListener()
It will add the one-time listener to the beginning of the array.
Syntax:
eventEmitter.prependOnceListener(event, listener)
eventEmitter.prependListener()
It will add the listener to the beginning of the array.
Syntax:
eventEmitter.prependListener(event, listener)
Now, let us understand with the help of the example:
javascript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Declaring listener fun1 to myEvent1
var fun1 = (msg) => {
console.log("Message from fun1: " + msg);
};
// Declaring listener fun2 to myEvent2
var fun2 = (msg) => {
console.log("Message from fun2: " + msg);
};
// Listening to myEvent with fun1 and fun2
eventEmitter.addListener('myEvent', fun1);
// fun2 will be inserted in front of listeners array
eventEmitter.prependListener('myEvent', fun2);
// Listing listeners
console.log(eventEmitter.listeners('myEvent'));
// Count the listeners registered to myEvent
console.log(eventEmitter.listenerCount('myEvent'));
// Triggering myEvent
eventEmitter.emit('myEvent', 'Event occurred');
Output:
[ [Function: fun2], [Function: fun1] ]
2
Message from fun2: Event occurred
Message from fun1: Event occurred
Special Events
All EventEmitter instances emit the event ‘newListener’ when new listeners are added and ‘removeListener’ existing listeners are removed.
- Event: ‘newListener’ This event is emitted when a new listener is added. It’s triggered before the listener is added to the internal array.
eventEmitter.once( 'newListener', listener)
eventEmitter.on( 'newListener', listener)
- Event: ‘removeListener’ The ‘removeListener’ event is emitted after a listener is removed.
eventEmitter.once( ‘removeListener’, listener)
eventEmitter.on( 'removeListener’, listener)
- Event: ‘error’ When an error occurs, the ‘error’ event is emitted. If no listener is attached to this event, Node.js will throw an error and terminate the process.
eventEmitter.on('error', listener)
javascript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Register to error
eventEmitter.on('error', (err) => {
console.error('whoops! there was an error');
});
// Register to newListener
eventEmitter.on( 'newListener', (event, listener) => {
console.log(`The listener is added to ${event}`);
});
// Register to removeListener
eventEmitter.on( 'removeListener', (event, listener) => {
console.log(`The listener is removed from ${event}`);
});
// Declaring listener fun1 to myEvent1
var fun1 = (msg) => {
console.log("Message from fun1: " + msg);
};
// Declaring listener fun2 to myEvent2
var fun2 = (msg) => {
console.log("Message from fun2: " + msg);
};
// Listening to myEvent with fun1 and fun2
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun2);
// Removing listener
eventEmitter.off('myEvent', fun1);
// Triggering myEvent
eventEmitter.emit('myEvent', 'Event occurred');
// Triggering error
eventEmitter.emit('error', new Error('whoops!'));
Output:
The listener is added to removeListener
The listener is added to myEvent
The listener is added to myEvent
The listener is removed from myEvent
Message from fun2: Event occurred
whoops! there was an error
Asynchronous events
The EventEmitter calls all listeners synchronously in order to which they were registered. However, we can perform asynchronous calls by using setImmediate() or process.nextTick().
javascript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
// Async function listening to myEvent
eventEmitter.on('myEvent', (msg) => {
setImmediate( () => {
console.log("Message from async: " + msg);
});
});
// Declaring listener fun to myEvent
var fun = (msg) => {
console.log("Message from fun: " + msg);
};
// Listening to myEvent with fun
eventEmitter.on('myEvent', fun);
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
Output:
Message from fun: Event occurred
Message from async: Event occurred
Why Are Events Important in NodeJS?
- Asynchronous Nature: Events allow NodeJS to handle multiple tasks simultaneously without blocking the main thread.
- Scalability: They help manage numerous connections or operations at the same time, improving application performance.
- Flexibility: Custom events can be defined and handled based on specific requirements.
When Should You Use Events?
- Trigger Actions: Use events when specific actions need to occur in response to events like user actions, data streams, or network requests.
- Modular Code: Events help decouple different parts of your application, making the code cleaner and more maintainable.
Conclusion
Node.js events, along with the EventEmitter
class, enable powerful asynchronous handling in applications. You can create custom events, register listeners, emit events, and even manage listener lifecycle efficiently. Understanding these methods will help you build scalable and event-driven applications.
Similar Reads
Node Event Loop
The event loop in Node.js is a mechanism that allows asynchronous tasks to be handled efficiently without blocking the execution of other operations. It: Executes JavaScript synchronously first and then processes asynchronous operations.Delegates heavy tasks like I/O operations, timers, and network
6 min read
Node.js EventEmitter
The EventEmitter class in NodeJS is a core module that provides a way to handle asynchronous events. It allows objects to emit events and other objects to listen and respond to those events. Event Emitter in NodeNodeJS uses an events module to create and handle custom events. The EventEmitter class
5 min read
Node.js Examples
The following Node.js section contains a wide collection of Node.js examples. These Node.js examples are categorized based on the topics including file systems, methods, and many more. Each program example contains multiple approaches to solve the problem. Prerequisite: Node.js TutorialTable of Cont
2 min read
Essence of Node.js
Node.js or Node has a small core group of modules, commonly referred to as the Node Core that is exposed as the public Node API by using we write our applications or we can say that the Node Core implements the public Node API. Some examples of the modules present in the node core are: To work with
8 min read
JavaScript onmouse Events
The onmouse event is used to define the operation using the mouse. JavaScript onmouse events are: onmouseover and onmouseoutonmouseup and onmousedownonmouseenter and onmouseleave JavaScript onmouseover and onmouseout: The onmouseover and onmouseout events occur when the mouse cursor is placed over s
1 min read
Node.js Process exit Event
The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine. The process.exit() method is the method that is used to end the Node.js process. Every process action on the machi
2 min read
Node.js Process Signal Events
Signals are a POSIX (The Portable Operating System Interface) intercommunication system. These events will be emitted when Node receives signal events. In order to notify that an event has occurred, a notification is sent. The signal handler will receive the signal's name and the signal name is uppe
3 min read
Node.js Inspector
What is inspector in Node.js? Inspector in node.js is a debugging interface for node.js application that is contained in the app.js file and used blink developer tools. It works almost similar to chrome developer tools. It can support almost all the feature that a debugger generally have such as nav
3 min read
Node.js Basics
NodeJS is a powerful and efficient open-source runtime environment built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server side, which helps in the creation of scalable and high-performance web applications. In this article, we will discuss the NodeJs Basics and
7 min read
What is EventEmitter in Node.js ?
Node.js is known for its asynchronous, event-driven architecture, which allows for handling multiple operations without blocking the execution of other tasks. At the heart of this architecture is the EventEmitter class from the events module. It is a fundamental component that underpins many of Node
5 min read