Node.js is built around an event-driven architecture.
Almost everything in Node.js is based on events.
For example:
- A user sends an HTTP request.
- A file finishes reading.
- A database query completes.
- A timer expires.
- A socket receives data.
Each of these actions triggers an event, and Node.js responds by executing the appropriate code.
This event-driven model is one of the main reasons Node.js can efficiently handle thousands of concurrent connections.
In this article, we'll learn how the Events module works and how to create our own custom events using the EventEmitter class.
Let's get started!
What is the Events Module?
The Events module is a built-in Node.js module that allows you to create, emit, and listen for custom events.
Using the Events module, you can:
- Create custom events
- Listen for events
- Pass data with events
- Execute code when an event occurs
- Remove event listeners
- Handle one-time events
- Handle error events
Since it's built into Node.js, you don't need to install anything.
Importing the Events Module
const EventEmitter = require("events");
Or, using ES Modules:
import EventEmitter from "node:events";
What is EventEmitter?
EventEmitter is a class provided by the Events module.
It allows us to:
- Create events
- Listen for events
- Trigger events
Think of it like this:
Event Created
↓
Someone Listens
↓
Event Happens
↓
Listener Executes
Creating an EventEmitter Object
Before using events, create an instance of the EventEmitter class.
const EventEmitter = require("events");
const emitter = new EventEmitter();
Now, emitter can create and handle events.
Understanding on()
What is on()?
The on() method registers an event listener.
Syntax:
emitter.on(eventName, callback);
eventName→ Name of the eventcallback→ Function to execute
Step 1: Listen for an Event
Create a file:
app.js
Add the following code:
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("greet", () => {
console.log("Hello, Welcome to Node.js!");
});
Nothing happens yet.
Why?
Because we've only registered the listener.
We haven't triggered the event.
Understanding emit()
What is emit()?
emit() triggers an event.
Syntax:
emitter.emit(eventName);
Step 2: Emit the Event
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("greet", () => {
console.log("Hello, Welcome to Node.js!");
});
emitter.emit("greet");
Run:
node app.js
Output:
Hello, Welcome to Node.js!
Explanation
- Listener is registered.
- Event is emitted.
- Callback executes.
Emit an Event Multiple Times
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("hello", () => {
console.log("Hello!");
});
emitter.emit("hello");
emitter.emit("hello");
emitter.emit("hello");
Output:
Hello!
Hello!
Hello!
Each emit() triggers the listener.
Passing Data with Events
Events can pass data to listeners.
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("user", (name) => {
console.log(`Welcome ${name}`);
});
emitter.emit("user", "John");
Output:
Welcome John
Passing Multiple Values
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("student", (name, age) => {
console.log(`${name} is ${age} years old.`);
});
emitter.emit("student", "Emma", 22);
Output:
Emma is 22 years old.
Using Objects
Instead of passing multiple arguments, you can pass an object.
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("login", (user) => {
console.log(user.name);
console.log(user.email);
});
emitter.emit("login", {
name: "John",
email: "john@example.com",
});
Output:
John
john@example.com
Passing objects makes your code easier to read and extend.
Multiple Listeners for the Same Event
One event can have multiple listeners.
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("order", () => {
console.log("Order Received");
});
emitter.on("order", () => {
console.log("Payment Verified");
});
emitter.on("order", () => {
console.log("Email Sent");
});
emitter.emit("order");
Output:
Order Received
Payment Verified
Email Sent
Listeners execute in the order they were registered.
Understanding once()
What is once()?
once() registers a listener that executes only one time.
After the first execution, it is automatically removed.
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.once("login", () => {
console.log("User Logged In");
});
emitter.emit("login");
emitter.emit("login");
emitter.emit("login");
Output:
User Logged In
Even though the event is emitted three times, the listener runs only once.
Understanding off() / removeListener()
Sometimes you no longer want a listener.
const EventEmitter = require("events");
const emitter = new EventEmitter();
function greet() {
console.log("Hello");
}
emitter.on("welcome", greet);
emitter.off("welcome", greet);
emitter.emit("welcome");
Output:
(no output)
off() removes the listener.
Note:
off()is an alias forremoveListener()in modern Node.js versions.
Using removeAllListeners()
Remove every listener associated with an event.
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("test", () => console.log("Listener 1"));
emitter.on("test", () => console.log("Listener 2"));
emitter.removeAllListeners("test");
emitter.emit("test");
Output:
(no output)
Counting Event Listeners
You can check how many listeners are attached to an event.
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("message", () => {});
emitter.on("message", () => {});
console.log(emitter.listenerCount("message"));
Output:
2
Getting Event Names
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("login", () => {});
emitter.on("logout", () => {});
console.log(emitter.eventNames());
Output:
[ 'login', 'logout' ]
Error Events
Node.js treats "error" as a special event.
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("error", (error) => {
console.log("Error:", error.message);
});
emitter.emit("error", new Error("Database Connection Failed"));
Output:
Error: Database Connection Failed
Important: If you emit an
"error"event without an error listener, Node.js will throw the error and terminate the process.
Build a User Registration System
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("register", (user) => {
console.log(`Welcome ${user.name}`);
});
emitter.on("register", (user) => {
console.log(`Verification email sent to ${user.email}`);
});
emitter.on("register", (user) => {
console.log("Account Created Successfully");
});
emitter.emit("register", {
name: "John",
email: "john@example.com",
});
Output:
Welcome John
Verification email sent to john@example.com
Account Created Successfully
This demonstrates how one event can trigger multiple independent actions.
Build an Order Processing System
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("orderPlaced", () => {
console.log("Order Saved");
});
emitter.on("orderPlaced", () => {
console.log("Inventory Updated");
});
emitter.on("orderPlaced", () => {
console.log("Invoice Generated");
});
emitter.on("orderPlaced", () => {
console.log("Customer Notified");
});
emitter.emit("orderPlaced");
Output:
Order Saved
Inventory Updated
Invoice Generated
Customer Notified
This pattern is commonly used in large applications where different parts of the system react to the same event independently.
EventEmitter vs Normal Function Calls
Normal Function
function greet() {
console.log("Hello");
}
greet();
The function is called directly.
EventEmitter
emitter.on("greet", () => {
console.log("Hello");
});
emitter.emit("greet");
The function runs only when the event is emitted.
This makes your application more flexible and loosely coupled.
Real-World Use Cases
The Events module is widely used for:
- HTTP Servers
- File Streams
- Database Connections
- WebSocket Applications
- Chat Applications
- Notification Systems
- Logging Systems
- Payment Processing
- Background Jobs
Many built-in Node.js modules, such as Streams, are based on EventEmitter.
Common EventEmitter Methods
on() - Register an event listener
emit() - Trigger an event
once() - Register a one-time listener
off() - Remove a listener
removeListener() - Remove a listener (same as off())
removeAllListeners() - Remove all listeners for an event
listenerCount() - Count listeners for an event
eventNames() - Get all registered event names
Best Practices
When working with the Events module:
- Use meaningful event names such as
"userRegistered"or"orderPlaced". - Remove listeners that are no longer needed to avoid memory leaks.
- Use
once()for events that should only happen once. - Always register an
"error"listener if your emitter may emit errors. - Pass objects instead of many individual arguments when sending event data.
Common Beginner Mistakes
Here are some common mistakes developers make:
- Registering a listener but forgetting to call
emit(). - Emitting an
"error"event without an error listener. - Creating too many listeners without removing unused ones.
- Using events when a simple function call would be sufficient.
- Passing too many positional arguments instead of a single object.
Final Thoughts
The Events module is one of the foundations of Node.js. It enables applications to communicate through events, making them more modular, flexible, and scalable.
In this article, you learned:
- What the Events module is
- How
EventEmitterworks - How to register listeners using
on() - How to trigger events using
emit() - How to pass data with events
- How to use
once()for one-time listeners - How to remove listeners
- How to handle error events
- Practical examples and best practices
As you continue learning Node.js, you'll discover that many core modules—such as Streams, HTTP servers, and networking APIs—are built on top of EventEmitter. Understanding it will help you better understand how Node.js works internally and how to build event-driven applications.
Happy Coding! 🚀