EventEmitter in Node.js
Learn how to create an EventEmitter, register event listeners, emit events, and pass data between parts of a Node.js application.
In the previous lesson, we learned what events are and how event-driven programming works.
Node.js provides the built-in node:events module, which includes the
EventEmitter class. We can use it to create named events and run callback
functions when those events are emitted.
1. What Is EventEmitter?
EventEmitter is a class from Node.js's built-in events module.
An EventEmitter object lets us register functions as listeners and notify those listeners
when a named event occurs.
Think of a Task Manager application. When a task is added, the application can emit a
taskAdded event. A listener can respond by displaying a message or recording
the activity.
on() registers a listener, while emit()
emits an event and calls the listeners registered for that event.
2. Importing EventEmitter
The events module is included with Node.js, so you do not need to install an
external npm package. In a CommonJS project, import it using require().
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
Understanding the Code
| Code | Meaning |
|---|---|
require("node:events") | Loads Node.js's built-in events module. |
EventEmitter | Refers to the class used to create event-emitting objects. |
new EventEmitter() | Creates an object that can register and emit events. |
The node: prefix explicitly identifies a built-in Node.js module.
3. First EventEmitter Program
Let's register a listener for an event named welcome and then emit that event.
Step 1: Create a File
Create a JavaScript file named eventEmitter.js.
Step 2: Write the Program
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.on("welcome", () => {
console.log("Welcome to Node.js EventEmitter!");
});
emitter.emit("welcome");
Step 3: Run the Program
node eventEmitter.jsStep 4: Expected Output
Welcome to Node.js EventEmitter!Step 5: Understand the Code
new EventEmitter()creates an emitter object.emitter.on("welcome", ...)registers a listener for thewelcomeevent.() => { ... }is the callback function that runs when the event is emitted.emitter.emit("welcome")emits the event and invokes the registered listener.
emit() matches the event name registered with on().4. EventEmitter Flow Diagram
The following flow shows how an EventEmitter calls a registered listener.
1. Create Emitter
new EventEmitter()
2. Register Listener
emitter.on("welcome", callback)
3. Emit Event
emitter.emit("welcome")
4. Listener Executes
The callback displays the welcome message.
EventEmitter listeners are called synchronously, in registration order, when the event is emitted. A listener can schedule asynchronous work if needed.
5. Passing Data to an Event Listener
We can pass values to a listener by providing them as additional arguments to
emit(). The listener receives those values as function parameters.
Example: Task Added Event
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.on("taskAdded", (taskName) => {
console.log("New task added: " + taskName);
});
emitter.emit("taskAdded", "Learn Node.js");
Output
New task added: Learn Node.jsExplanation: The value "Learn Node.js" is passed as the second argument to emit(). The listener receives it in the taskName parameter.
6. Registering Multiple Listeners
More than one listener can be registered for the same event. When the event is emitted, the listeners run in the order in which they were registered.
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.on("taskCompleted", () => {
console.log("Task completion recorded.");
});
emitter.on("taskCompleted", () => {
console.log("Congratulations! Task completed.");
});
emitter.emit("taskCompleted");
Output
Task completion recorded.
Congratulations! Task completed.
Both callbacks respond to the same taskCompleted event. This is useful when different parts of an application need to react to one occurrence.
7. Using once() for a One-Time Listener
The once() method registers a listener that runs only the first time the specified event is emitted.
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.once("start", () => {
console.log("The process has started.");
});
emitter.emit("start");
emitter.emit("start");
Output
The process has started.Although start is emitted twice, the listener runs only once because it was registered with once().
8. Important EventEmitter Methods
| Method | Purpose |
|---|---|
on(eventName, listener) | Registers a listener for an event. |
emit(eventName, ...args) | Emits an event and optionally passes arguments to listeners. |
once(eventName, listener) | Registers a listener that runs at most once. |
off(eventName, listener) | Removes a specific listener from an event. |
removeAllListeners(eventName) | Removes listeners for the specified event; without an event name, removes all listeners from that emitter. |
We will explore registering, emitting, and removing events in the next lessons.
Important Points
EventEmitteris available from Node.js's built-innode:eventsmodule.on()registers a listener andemit()emits an event.- The event name used by
on()must match the name passed toemit(). - Extra arguments passed to
emit()are received by listener parameters. once()registers a listener that runs only once.
Summary
In this lesson, we learned that Node.js EventEmitter objects let us register
listeners and emit named events. We created an emitter, used on() to register
a callback, used emit() to trigger it, passed data to a listener, registered
multiple listeners, and used once() for a one-time response. These basics
prepare us to work with event registration and emission in more detail.