Updated March 21, 2023
Introduction to Events in Node.js
As we know, Node.js applications are event-driven. The name “Event” itself describes its meaning as something that “happens” or “occurs”. Events in Node.js are similar to the concept of the callback function in Node.js. The only difference is that callback function executes once the asynchronous function returns its results, whereas events are triggered on its corresponding event handler.
Today we will look into the “Events” module provided by Node.js, which consists of the “EventEmitter” class that enables us to implement event-driven programming. We will have a quick look at various methods provided by the EventEmitter class and also how event-driven programming makes Node.js fast and gives high performance.
How do Events work in Node.js?
Node.js events follow the below concepts:
- Since Node.js applications are event-driven, the events are triggered on its associated event handler.
- An event handler is nothing but a callback function called when an event is triggered.
- The main loop listens to the event triggers and then calls the corresponding event handler.
The EventEmitter class calls all the events synchronously in the order that they were registered. It ensures the proper sequencing of events and helps us avoid logic errors. When in need, we can switch to asynchronous by using setImmediate() or process.nextTick() method.
One of the methods which fire an event is known as emit() that belongs to the EventEmitter class. The emit() method has the first argument as the name of the event and the next arguments are used to pass data. The on() method listens to the event that is emitted and executes it.
Let us understand the Event Emitter class and its methods through the following code snippet:
Steps
Step 1: Import the “events”.
Step 2: Create an instance of “EventEmitter”
Step 3: Use the instance of EventEmitter class to implement the emit() method, which fires an event called “messageLogged” in the code below. The first argument in the emit() method is the event name.
Step 4: Use the same instance of EventEmitter class to listen to the event “messageLogged” by using the on(). The first argument in the on() is the event name and the second is the event handler of the event.
Code snippet:
const EventEmitter = require('events') const emitter =
new EventEmitter() emitter.once('messageLogged',
function(){ console.log("Listening to the event messageLogged")
})
emitter.emit('messageLogged')
5. When the above code snippet is executed, we receive the following output:
Thus the above code snippet demonstrated the raising of event using emit() and listening to an event by on().
a. Let us have a look at how an event can be handled once:
Code snippet:
const EventEmitter = require('events') const
emitter = new EventEmitter() var n = 0
emitter.on('increment_number', function(){
console.log(++n)
})
emitter.emit('increment_number')
emitter.emit('increment_number')
In the implementation of events, when the listener is registered using the emitter.on() method, that listener will be invoked every time the named event is emitted; in the above example the event name is “increment_number” which is being emitted twice with the help of emit() method, thus the listener is the invoked twice.
The following output is received upon executing the above code snippet:
b. In the below code, we will be making use of emitter.once() method. The emitter.once() method enables us the ability to register a listener that is called at most once for a particular event. Once the event is emitted for the first time the listener is unregistered and then it is called.
Code snippet:
const EventEmitter = require('events') const
emitter = new EventEmitter() var n = 0
emitter.once('increment_number', function(){
console.log(++n)
})
emitter.emit('increment_number')
emitter.emit('increment_number')
In the above example, we have registered the listener using a once() method, which will be called only once. As seen in the output below, it only prints 1, because, for the second time when the event is emitted, the listener is unregistered. So the output of only the first emit() method is printed.
Methods in Events
- emit(event, [arg1], [arg2], [arg3],….[]): emit() is used to raise an event. The first argument event is the name of the event.
- on(event, listener): on() listens to the event and executes the event handler. The listener is the event handler.
- once(event, listener): once() adds a one time listener.
- addListener(event, listener): addListener() adds a listener to the end of listeners array for the specified event.
- removeListener(event, listener): removeListener() removes a listener from the listener’s array for the specified event.
- removeAllListeners([event]): removeAllListeners() removes all the listeners of the specified events.
- listeners(event): listeners() returns an array of the specified event.
- setMaxListeners(n): If more than 10 listeners are added to the event, the EventEmitter class gives a warning by default. This function allows the number of listeners to increase, in order to do so set the value to zero for unlimited.
- Modules in Node.js: Modules in Node.js can be considered as a set of functions that we would like to include in our application. It is similar to a set of JavaScript libraries. Each module in Node.js has its own context and cannot interfere with any other modules. These modules can be reused throughout the Node.js application. We need to use the require() function to include our module with the module name in it.
Types of Modules
Here are the following types of Modules mention below
1. Built-in modules: Node.js consists of various built-in modules, which we can use without any further installation. Few built-in modules are HTTP (HyperText Transfer Protocol), URL, path, events, fs (file system), querystring, etc.
2. Local modules: The local modules are the once which are created locally in our Node.js application. These modules can contain different functionalities in separate files or folders and can be reused throughout the Node.js application. To expose a particular module or a function we can use “module. exports”. The module. exports object is present in every JS file by default.
Conclusion – Events in Node.Js
Thus we studied how event-driven programming can be implemented in Node.js through the events module. By using EventEmitter class and its methods we demonstrated the raising of an event and listening to it and had a look at modules.
Recommended Articles
This is a guide to Events in Node.Js. Here we discuss How do Events work in Node.js? along with the types of Modules and Methods in Events. You can also go through our other suggested articles to learn more –