Introduction
Events are an important part of Node.js because many Node.js operations happen asynchronously. The EventEmitter class allows your program to create events and respond to them using listeners. In this chapter, you will practice creating events, listening for events, passing data to listeners, handling multiple listeners, removing listeners, and building a small practical event-based program. Node.js Events and Event emitter practice questions with solutions help to understand the concepts.
Question 1: How do you create an EventEmitter object?
Problem
Create an EventEmitter object and display a message.
Solution
const EventEmitter = require("events");
const emitter = new EventEmitter();
console.log("EventEmitter created successfully.");
Output
EventEmitter created successfully.
Step-by-Step Explanation
- Import
EventEmitterfrom the built-ineventsmodule. - Create a new
EventEmitterobject. - Store it inside the
emittervariable. - The object can now create and handle custom events.
The basic pattern is:
const EventEmitter = require("events");
const emitter = new EventEmitter();
Question 2: How do you create and listen for a custom event?
Problem
Create an event named welcome and display a message whenever the event occurs.
Solution
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("welcome", () => {
console.log("Welcome to Node.js!");
});
emitter.emit("welcome");
Output
Welcome to Node.js!
Step-by-Step Explanation
- Import
EventEmitter. - Create an emitter object.
- Use
.on()to create an event listener. "welcome"is the event name.- The function runs when the event occurs.
- Use
.emit()to trigger the event. - The listener executes.
The two important methods are:
emitter.on();
and:
emitter.emit();
on() listens for an event, while emit() triggers an event.
Question 3: How do you pass data with an event?
Problem
Create a student event and send a student’s name to the event listener.
Solution
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("student", (name) => {
console.log("Student Name:", name);
});
emitter.emit("student", "Riya");
Output
Student Name: Riya
Step-by-Step Explanation
- Create an
EventEmitter. - Listen for the
studentevent. - Add a
nameparameter to the listener function. - Trigger the event using
.emit(). - Pass
"Riya"as event data. - The listener receives
"Riya".
You can pass different values:
emitter.emit("student", "Aman");
Output:
Student Name: Aman
Question 4: How do you pass multiple values with an event?
Problem
Create a result event and pass the student’s name and marks.
Solution
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("result", (name, marks) => {
console.log("Name:", name);
console.log("Marks:", marks);
});
emitter.emit("result", "Aarav", 85);
Output
Name: Aarav
Marks: 85
Step-by-Step Explanation
- Create an
EventEmitter. - Add a listener for the
resultevent. - Define two parameters:
nameandmarks. - Emit the event.
- Pass
"Aarav"as the first value. - Pass
85as the second value. - The listener receives both values.
You can pass multiple arguments with emit().
Question 5: How do you pass an object through an event?
Problem
Send complete student information through an event.
Solution
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("student", (student) => {
console.log("Name:", student.name);
console.log("Age:", student.age);
console.log("Course:", student.course);
});
const studentData = {
name: "Riya",
age: 18,
course: "Node.js"
};
emitter.emit("student", studentData);
Output
Name: Riya
Age: 18
Course: Node.js
Step-by-Step Explanation
- Create an event listener.
- The listener receives a
studentobject. - Create an object containing student information.
- Trigger the
studentevent. - Pass the object to
.emit(). - Access object properties inside the listener.
This approach is useful when an event needs to carry several related values.
Question 6: How do you create multiple listeners for one event?
Problem
Create two listeners for the same login event.
Solution
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("login", () => {
console.log("User logged in.");
});
emitter.on("login", () => {
console.log("Login activity recorded.");
});
emitter.emit("login");
Output
User logged in.
Login activity recorded.
Step-by-Step Explanation
- Create an
EventEmitter. - Add the first listener for
login. - Add another listener for the same event.
- Trigger the event using
.emit(). - Both listeners execute.
By default, listeners for the same event are called in the order in which they were registered.
Question 7: How do you listen to an event only once?
Problem
Create a welcome event that should execute its listener only the first time the event is emitted.
Solution
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.once("welcome", () => {
console.log("Welcome! This message appears only once.");
});
emitter.emit("welcome");
emitter.emit("welcome");
emitter.emit("welcome");
Output
Welcome! This message appears only once.
Step-by-Step Explanation
- Create an
EventEmitter. - Use
.once()instead of.on(). - Register the
welcomeevent. - Emit the event three times.
- The listener executes only during the first emission.
- After that, the listener is automatically removed.
Difference
Use:
emitter.on("event", listener);
when the listener should continue responding to the event.
Use:
emitter.once("event", listener);
when the listener should respond only once.
Question 8: How do you remove an event listener?
Problem
Create a listener for a message event and then remove it before triggering the event.
Solution
const EventEmitter = require("events");
const emitter = new EventEmitter();
function showMessage() {
console.log("Hello from Node.js!");
}
emitter.on("message", showMessage);
emitter.removeListener(
"message",
showMessage
);
emitter.emit("message");
Output
There will be no output because the listener was removed before the event was emitted.
Step-by-Step Explanation
- Create an emitter.
- Create a named function called
showMessage. - Register it using
.on(). - Use
removeListener()to remove that exact listener. - Emit the event.
- Nothing happens because the listener no longer exists.
You can also use:
emitter.off("message", showMessage);
to remove a listener.
Question 9: How do you count the listeners attached to an event?
Problem
Create three listeners for a notification event and find out how many listeners are attached.
Solution
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("notification", () => {
console.log("Notification 1");
});
emitter.on("notification", () => {
console.log("Notification 2");
});
emitter.on("notification", () => {
console.log("Notification 3");
});
console.log(
"Number of listeners:",
emitter.listenerCount("notification")
);
Output
Number of listeners: 3
Step-by-Step Explanation
- Create an emitter.
- Register three listeners for
notification. - Use
listenerCount(). - Pass the event name.
- Node.js returns the number of listeners attached to that event.
You can also trigger the event:
emitter.emit("notification");
which will execute all three listeners.
Question 10: How do you create a practical user registration event system?
Problem
Create a simple registration system that:
- Receives user information.
- Emits a
userRegisteredevent. - Displays a welcome message.
- Sends a simulated email message.
- Records the registration activity.
Solution
const EventEmitter = require("events");
const emitter = new EventEmitter();
// Listener 1
emitter.on("userRegistered", (user) => {
console.log(
`Welcome ${user.name}!`
);
});
// Listener 2
emitter.on("userRegistered", (user) => {
console.log(
`Email sent to ${user.email}`
);
});
// Listener 3
emitter.on("userRegistered", (user) => {
console.log(
`Registration recorded for ${user.name}`
);
});
// User data
const user = {
name: "Riya",
email: "riya@example.com"
};
// Trigger event
emitter.emit("userRegistered", user);
Output
Welcome Riya!
Email sent to riya@example.com
Registration recorded for Riya
Step-by-Step Explanation
- Import
EventEmitter. - Create an emitter object.
- Create a
userRegisteredevent. - Add the first listener to display a welcome message.
- Add the second listener to simulate sending an email.
- Add the third listener to record the registration.
- Create a user object.
- Emit the
userRegisteredevent. - Pass the user object to the event.
- All registered listeners respond to the same event.
Why is this useful?
Imagine a real application where a user registers. One event could trigger several independent tasks:
User Registration
|
├── Welcome message
|
├── Email notification
|
└── Activity logging
This is one of the important ideas behind event-driven programming in Node.js.
Key Takeaways
- Node.js uses an event-driven programming model.
- The built-in
eventsmodule providesEventEmitter. - Create an emitter with
new EventEmitter(). .on()registers an event listener..emit()triggers an event..once()runs a listener only one time.- Event listeners can receive data from
emit(). - You can pass multiple arguments to an event.
- You can also pass objects through events.
- Multiple listeners can listen for the same event.
removeListener()removes a specific listener..off()can also be used to remove a listener.listenerCount()tells you how many listeners are registered for an event.- Event names can be custom strings such as
login,logout,orderCreated, oruserRegistered. - EventEmitter is useful for building loosely connected parts of an application.
- Events are an important concept for understanding Node.js and asynchronous programming.
FAQs
1. What is EventEmitter in Node.js?
EventEmitter is a class provided by Node.js’s built-in events module. It allows you to create custom events and register functions that run when those events occur.
const EventEmitter = require("events");
const emitter = new EventEmitter();
2. What is the difference between on() and emit()?
on() registers a listener for an event:
emitter.on("login", () => {
console.log("User logged in.");
});
emit() triggers the event:
emitter.emit("login");
So, on() listens and emit() triggers.
3. How do you pass data to an EventEmitter listener?
Pass the data as arguments to emit():
emitter.emit(
"student",
"Riya",
18
);
Receive the values in the listener:
emitter.on(
"student",
(name, age) => {
console.log(name);
console.log(age);
}
);
4. What does once() do in Node.js EventEmitter?
once() registers a listener that runs only one time.
emitter.once("welcome", () => {
console.log("Welcome!");
});
Even if the event is emitted multiple times, the listener runs only during the first emission.
5. Can multiple listeners listen for the same event?
Yes. You can register multiple listeners for the same event.
emitter.on("login", () => {
console.log("Login successful.");
});
emitter.on("login", () => {
console.log("Login activity recorded.");
});
When login is emitted, both listeners will normally execute in registration order.
6. How do you remove an EventEmitter listener?
You can use removeListener() or off().
function welcome() {
console.log("Welcome!");
}
emitter.on("login", welcome);
emitter.removeListener(
"login",
welcome
);
The listener function must be the same function reference that was originally registered.
7. Where is EventEmitter used in real Node.js applications?
EventEmitter is useful when different parts of an application need to respond to the same event. Common examples include user registration, login activity, orders, notifications, logging, file processing, and application lifecycle events.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
