Node.js – Events Module
Subject: nodejs
Node.js – Events Module
Node.js is built on an event-driven architecture, making it highly efficient and suitable for asynchronous programming. The events
module enables Node.js to create, handle, and respond to custom events, similar to event listeners in browser JavaScript.
This module is part of the Node.js core—no installation needed.
Why Use the events
Module?
- Emit and listen to custom application events
- Build loosely coupled, modular systems
- Cleanly handle asynchronous logic
- Backbone of core Node.js modules like
http
,net
,fs
, andstream
Importing the Events Module
Creating an Event Emitter
You can now use emitter
to emit and listen for events.
1. Listening to an Event using .on()
.on(eventName, callback)
registers a listener.
.emit(eventName)
triggers the event.
2. Passing Data with Events
You can pass multiple arguments to listeners if needed.
3. Using .once()
for One-Time Listeners
Use for setup or one-time tasks.
4. Removing Event Listeners
5. Counting Listeners
6. EventEmitter in a Custom Class
Real-World Use Case: HTTP Server Events
In this example, every request triggers the request
event.
Key Takeaways
- The
events
module supports custom event handling in Node.js EventEmitter
is used to emit and listen to events- Use
.on()
,.emit()
,.once()
,.off()
for event workflows - Useful for building asynchronous, modular applications