Registering Events in Node.js
Learn how to register event listeners in Node.js using on() and once(), handle named events, and respond to application actions.
In the previous lesson, we learned about the EventEmitter class.
Now, we will learn how to register event listeners. A listener is
a callback function that executes when its associated event is
emitted. Node.js provides methods such as on() and
once() to register listeners.
1. What Is Registering an Event?
Registering an event means telling an EventEmitter which function should execute when a particular event is emitted.
For example, in our Task Manager application, we can register a
listener for the taskAdded event. When a new task
is added and the event is emitted, the registered function
displays a confirmation message.
2. Using the on() Method
The on() method registers a listener for a named
event. The listener executes whenever that event is emitted,
provided the listener remains registered.
Syntax
emitter.on("eventName", callbackFunction);
Understanding the Syntax
| Part | Meaning |
|---|---|
emitter |
The EventEmitter object. |
on() |
Registers an event listener. |
"eventName" |
The name of the event to listen for. |
callbackFunction |
The function that executes when the event is emitted. |
3. Registering Your First Event Listener
Let's register a listener for an event named
welcome.
Step 1: Create a File
Create a JavaScript file named registerEvent.js.
Step 2: Write the Program
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.on("welcome", () => {
console.log("Welcome to Node.js!");
});
emitter.emit("welcome");
Step 3: Run the Program
node registerEvent.js
Step 4: Expected Output
Welcome to Node.js!
Step 5: Understand the Code
-
require("node:events")imports the built-in EventEmitter class. -
new EventEmitter()creates an emitter object. -
emitter.on("welcome", ...)registers the listener. -
emitter.emit("welcome")emits the event and executes the registered callback.
welcome event is emitted.
4. Event Listener Registration Flow
The following diagram explains the relationship between event registration and event emission.
1. Create EventEmitter
new EventEmitter()
2. Register Listener
emitter.on("welcome", callback)
3. Emit Event
emitter.emit("welcome")
4. Execute Callback
The registered function runs.
Note: Registering a listener and emitting an event are two separate operations. Register the listener before emitting the event if you want it to receive that emission.
5. Registering Multiple Event Listeners
We can register listeners for different event names on the same EventEmitter object. Each listener responds to its corresponding event.
Example: Task Manager
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.on("taskAdded", () => {
console.log("A new task was added.");
});
emitter.on("taskDeleted", () => {
console.log("A task was deleted.");
});
emitter.emit("taskAdded");
emitter.emit("taskDeleted");
Output
A new task was added.
A task was deleted.
Explanation:
The taskAdded listener executes when
taskAdded is emitted. Similarly, the
taskDeleted listener executes when
taskDeleted is emitted.
6. Registering a Named Callback Function
Instead of writing an anonymous arrow function inside
on(), we can define a named function and pass its
reference to the listener registration method.
Example
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
function handleTaskAdded() {
console.log("Task added successfully!");
}
emitter.on("taskAdded", handleTaskAdded);
emitter.emit("taskAdded");
Output
Task added successfully!
Here, handleTaskAdded is passed as a function
reference. We do not write
handleTaskAdded() inside on(),
because we want the EventEmitter to call it when the event
is emitted.
7. Registering a One-Time Listener with once()
The once() method registers a listener that executes
at most one time for the specified event. After the first
execution, that listener is automatically removed.
Example
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.once("userLogin", () => {
console.log("User login event handled.");
});
emitter.emit("userLogin");
emitter.emit("userLogin");
Output
User login event handled.
Although the event is emitted twice, the callback executes only
once because it was registered using once().
8. Difference Between on() and once()
| Feature | on() | once() |
|---|---|---|
| Purpose | Registers a regular listener. | Registers a one-time listener. |
| Number of executions | Can execute on every emission. | Executes at most once. |
| Automatic removal | Not automatically removed after execution. | Removed after its first execution. |
| Typical use | Repeated application events. | One-time initialization or notification. |
9. Common Mistake: Event Name Mismatch
A listener responds only to the event name for which it is registered. If we emit a different event name, that listener will not execute.
Incorrect Example
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.on("taskAdded", () => {
console.log("Task added!");
});
emitter.emit("taskDeleted");
Output
// No output
Why?
The listener is registered for taskAdded, but the
program emits taskDeleted. These are different
event names.
emitter.emit("taskAdded") if you want the
registered taskAdded listener to execute.
Important Points
-
on()registers a listener for an event. -
once()registers a listener that executes at most once. - Registering a listener does not automatically emit an event.
- The event name used in registration must match the emitted event name.
- Multiple listeners can be registered for different events or for the same event.
-
A named callback can be passed to
on()as a function reference.
Summary
In this lesson, we learned how to register event listeners
in Node.js using on() and once().
We created listeners for different events, used named
callback functions, compared regular and one-time listeners,
and understood why event names must match. In the next
lesson, we will learn how to emit events and pass data
to their listeners.