Custom Events in Node.js
Learn how to create custom events, register listeners, pass data through events, and build event-driven applications using practical CIIT Training Institute examples.
In the previous lesson, we learned how to remove event listeners using off(), removeListener(), and removeAllListeners(). In this lesson, we will learn how to create and use custom events with Node.js EventEmitter.
A custom event allows us to define an event name according to our application's requirements. For example, CIIT Training Institute can use events such as studentRegistered, courseEnquiryReceived, and paymentCompleted to represent different application activities.
1. What Are Custom Events?
A custom event is an event that we define for a specific purpose in our application. Node.js allows us to create custom event names and use EventEmitter to notify registered listeners when those events occur.
For example, when Samadhan registers a new student at CIIT
Training Institute, the application can emit a
studentRegistered event. A listener can respond
by displaying a confirmation message or performing another
application task.
Similarly, when Pradnya receives a course enquiry, the
application can emit a courseEnquiryReceived
event and pass the student's information to the listener.
2. Why Do We Use Custom Events?
Custom events allow different parts of an application to respond to important occurrences without requiring the code that emits the event to directly call every listener.
| Custom Event | When It Occurs | Possible Response |
|---|---|---|
studentRegistered |
A student registers for a course. | Display a registration confirmation. |
courseEnquiryReceived |
A student submits a course enquiry. | Display an enquiry notification. |
paymentCompleted |
A payment workflow confirms completion. | Display a payment confirmation. |
taskCompleted |
A task is marked as completed. | Record or display the completion status. |
3. Creating Your First Custom Event
To create a custom event, we first create an EventEmitter object, register a listener for our chosen event name, and then emit that event.
Step 1: Create a JavaScript File
Create a file named customEvents.js.
Step 2: Write the Program
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.on("studentRegistered", () => {
console.log("Student registered successfully at CIIT Training Institute!");
});
emitter.emit("studentRegistered");
Step 3: Run the Program
node customEvents.js
Step 4: Expected Output
Student registered successfully at CIIT Training Institute!
Step 5: Understand the Code
-
require("node:events")imports the built-in EventEmitter class. -
new EventEmitter()creates an emitter object. -
emitter.on("studentRegistered", ...)registers a listener for our custom event. -
emitter.emit("studentRegistered")emits the event and executes the registered listener.
4. Custom Event Flow Diagram
This diagram explains how a custom event works inside a Node.js application.
1. Create EventEmitter
new EventEmitter()
2. Register Custom Event Listener
emitter.on("studentRegistered", callback)
3. Emit Custom Event
emitter.emit("studentRegistered")
4. Execute Listener
Display the student registration message.
Note: The listener should be registered before the event is emitted if it needs to receive that emission.
5. Passing Data Through Custom Events
Custom events can carry information. We pass values as
additional arguments to emit(), and the listener
receives those values through its function parameters.
For example, Samadhan registers a student for a course. The application can emit the student's name and the course name.
Example: Student Registration
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.on("studentRegistered", (studentName, courseName) => {
console.log("Student Name: " + studentName);
console.log("Course Name: " + courseName);
});
emitter.emit(
"studentRegistered",
"Samadhan",
"Node.js Development"
);
Expected Output
Student Name: Samadhan
Course Name: Node.js Development
Understanding the Arguments
| Emitted Value | Listener Parameter |
|---|---|
"Samadhan" |
studentName |
"Node.js Development" |
courseName |
The first argument is received by studentName,
and the second argument is received by courseName.
6. Creating Multiple Custom Events
We can register multiple custom events on the same EventEmitter object. Each event can have its own listener and purpose.
In this example, Pradnya handles course enquiries while Samadhan handles student registration notifications.
Program
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.on("courseEnquiryReceived", (studentName) => {
console.log("Pradnya received an enquiry from " + studentName);
});
emitter.on("studentRegistered", (studentName) => {
console.log("Samadhan registered student " + studentName);
});
emitter.emit("courseEnquiryReceived", "Amit");
emitter.emit("studentRegistered", "Neha");
Expected Output
Pradnya received an enquiry from Amit
Samadhan registered student Neha
The first event invokes the course enquiry listener. The second event invokes the student registration listener. Each listener responds to its corresponding event name.
7. CIIT Training Institute Event Flow
This diagram shows how two different application activities can use custom events and separate listeners.
CIIT Training Institute Application
Student enquiry and registration activities
Course Enquiry
Emit courseEnquiryReceived
Display the enquiry notification.
Student Registration
Emit studentRegistered
Display the registration notification.
8. Best Practices for Custom Event Names
Choosing meaningful event names makes code easier to understand and maintain. Event names should clearly describe the occurrence that the application is reporting.
| Less Descriptive | More Descriptive | Reason |
|---|---|---|
event1 |
studentRegistered |
Clearly describes student registration. |
data |
courseEnquiryReceived |
Identifies the specific application occurrence. |
done |
paymentCompleted |
Explains what has been completed. |
action |
taskCompleted |
Makes the event's purpose clearer. |
studentRegistered and
courseEnquiryReceived are examples of
descriptive camelCase event names.
9. Common Mistakes with Custom Events
Mistake 1: Event Name Mismatch
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.on("studentRegistered", () => {
console.log("Student registered!");
});
emitter.emit("courseEnquiryReceived");
Output
// No output
The listener is registered for studentRegistered,
but the program emits courseEnquiryReceived.
Because the event names are different, the listener does not execute.
Mistake 2: Emitting Before Registering
const EventEmitter = require("node:events");
const emitter = new EventEmitter();
emitter.emit("studentRegistered");
emitter.on("studentRegistered", () => {
console.log("Student registered!");
});
Output
// No output
The event is emitted before the listener is registered. EventEmitter does not automatically replay that earlier event to listeners registered later.
Important Points
- Custom events are application-defined event names.
-
Node.js EventEmitter provides
on()andemit()to work with custom events. - Event names must match for the registered listener to respond.
-
Additional arguments passed to
emit()are received by listener parameters in order. - Multiple custom events can be managed by the same EventEmitter object.
- Emitting a custom event does not automatically persist data or perform external operations.
Summary
In this lesson, we learned how to create custom events in Node.js using EventEmitter. We registered listeners, emitted events, passed student and course information through callback arguments, created multiple custom events, and explored common mistakes involving event names and registration order. We also used CIIT Training Institute examples involving Samadhan and Pradnya to understand practical event-driven programming.