Node.js Events
Overview
If you have worked with JavaScript in the browser, you know how interaction with a user is handled through events like:- mouse clicks, keyboard button presses, etc.
Similar to that for events occurring on the backend side like- a request made to the server, a file opened, etc., Node.js handles those events using the Node.js Events module. So let's dive into this article to learn more about Node.js Events.
Introduction to the Node.js Events Module
Node.js follows asynchronous event-driven architecture. Node.js offers us the option to handle such events using the events module. Events are triggered by the objects (called "emitters") which in turn causes Function objects (called "listeners") to be called and if multiple listeners are listening to the same event then the listeners are called synchronously in the order they were registered.
For example: a fs.ReadStream emits an event when the file is opened, so by using listeners we can display a message ("file opened") on the console. All the objects which handle such events are instances of the EventEmitter class of the events module. So, let's look briefly into the Node.js Events module.
Useful Methods of Events Module
emit()
It will emit a named event. This method synchronously calls every event listener in the order they were registered. Syntax for emit() method:
on() or addListener()
The on() and addListener are similar methods. These are used to listen to the emitted named events. These methods add a callback function that's called when an event is emitted.
Syntax for on() or addListener() methods:
once():
It is used just like the addListener() and on() methods but allows for responding to the event only once i.e, The listener is invoked only the first time and never again.
Syntax for once() method:
removeListener() or off()
It will remove at most one instance of the specified listener which is in front of the listener's queue. Syntax for off() or removeListener() methods:
removeAllListeners()
It Removes all listeners of an EventEmitter object or those listening to the specific event.
Syntax for removeAllListener() methods:
prependListener(eventName, listener)
When you use on() or addListener() to add listeners, it’s added to the last of the listener's queue, and is also called last. Using prependListener(), the listener is added to the beginning of the listener's queue, and thus is called before other listeners. Syntax for prependListener() methods:
prependOnceListener()
When you add a listener using prependOnceListener(), it's added at the beginning of the listeners' array and is called at the beginning only one time. Using prependOnceListener it's added, and called, before other listeners. Syntax for prependOnceListener() methods:
setMaxListeners()
It sets the maximum number of listeners one can add to the eventEmitter object. By default, the value of maximum listeners is set to 10 but the value can be increased or decreased.
Syntax for setMaxListeners() methods:
getMaxListeners()
Get the maximum number of listeners one can add to an EventEmitter object, which defaults to 10 but it can be increased or lowered by using setMaxListeners(). Syntax for getMaxListeners() methods:
eventNames()
It returns an array of strings that represent the events registered on the current EventEmitter object.
Syntax for eventNames() methods:
listeners()
It returns an array of listeners for the event passed as a parameter.
Syntax for listeners() methods:
listenerCount()
It returns the number of listeners listening for the event passed as a parameter.
Syntax for listenerCount() methods:
The EventEmitter Class
EventEmitter is a class in the events module of Node.js and with an EventEmitter, we can simply raise a newly named event from a different part of an application, and when the event has been raised a listener will listen to that raised event and have some action performed for the event. The two main functions of EventEmitter are:-
- Emitting an event i.e., the trigger of an event.
- Listening to an event i.e., calling a callback function that’s going to be executed when the event is triggered.
Syntax for creating an eventEmitter class object:
Listening Events
Event Listeners handle the triggered events using the on(), addListener(), and once() methods. These methods fire off callback functions attached to it when the corresponding named event is triggered.
- Using on() or addListener() methods, listeners can be added multiple times if multiple calls are made to the same combination of event and listener.
- But the once() method allows for responding to the event only once i.e, The listener is invoked only the first time and never again.
Also, the event listener has these in-built events:
- newListener when a listener is added
- removeListener when a listener is removed
Syntax for on(), once() and addListener() methods:
Emitting Events
Triggering a named event can be done by the emit() method. This method synchronously calls every event listener in the order they were registered. So, corresponding event listeners need to be present before event emitters. We can pass arguments to the event handler by passing them as additional arguments to emit().
Syntax for emit() method:
Example of emitting and listening of events:
Output:
Example with arguments in emit method:
Output:
Removing Listener
Events module removes listeners using off(), removeListener(), removeAllListeners() methods. These methods remove the specified listener from the listener queue.
- Using the off() or removeListener() methods, we can remove at most one instance of a listener from the front of the listener queue.
- But the removeAllListeners() method removes all listeners of an EventEmitter object or those listening to the specific event.
Note:- We can use remove listener methods by saving the callback function to a variable.
Syntax for off(), removeListener() and removeAllListeners() methods:
Example:
Output:
Explanation: After triggering of event1, only one listener i.e., the listener with callback2 is executed since the listener with callback1 is removed as the listener with callback1 was the first listener in the queue.
Extend the EventEmitter Class
It is recommended to make our own event emitter instance using class inheritance. As sometimes, in writing an app inheritance may affect scalability and performance. Class inheritance in Node.js is achieved using extending the base class.
Example:
Output:
Sample Code to Implement Some of the Events Module Methods
Output:
Conclusion
- Events are Node.js modules that provide flexibility to the user to create, fire, and listen in the way the user desires.
- The Events module of Node.js provides us multiple functionalities that have got a variety of use cases when working on a real-time project like:
- defining different event listeners for the same event
- Passing an arbitrary number of arguments according to our need
- handling errors etc.
- The on() method is used to create an event listener usually consisting of a callback function and the emit() method is used to trigger an event.
- All the callback functions are listened to by Node synchronously.