Node.js Events and Event emitter Practice Questions with Solutions

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

  1. Import EventEmitter from the built-in events module.
  2. Create a new EventEmitter object.
  3. Store it inside the emitter variable.
  4. 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

  1. Import EventEmitter.
  2. Create an emitter object.
  3. Use .on() to create an event listener.
  4. "welcome" is the event name.
  5. The function runs when the event occurs.
  6. Use .emit() to trigger the event.
  7. 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

  1. Create an EventEmitter.
  2. Listen for the student event.
  3. Add a name parameter to the listener function.
  4. Trigger the event using .emit().
  5. Pass "Riya" as event data.
  6. 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

  1. Create an EventEmitter.
  2. Add a listener for the result event.
  3. Define two parameters: name and marks.
  4. Emit the event.
  5. Pass "Aarav" as the first value.
  6. Pass 85 as the second value.
  7. 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

  1. Create an event listener.
  2. The listener receives a student object.
  3. Create an object containing student information.
  4. Trigger the student event.
  5. Pass the object to .emit().
  6. 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

  1. Create an EventEmitter.
  2. Add the first listener for login.
  3. Add another listener for the same event.
  4. Trigger the event using .emit().
  5. 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

  1. Create an EventEmitter.
  2. Use .once() instead of .on().
  3. Register the welcome event.
  4. Emit the event three times.
  5. The listener executes only during the first emission.
  6. 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

  1. Create an emitter.
  2. Create a named function called showMessage.
  3. Register it using .on().
  4. Use removeListener() to remove that exact listener.
  5. Emit the event.
  6. 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

  1. Create an emitter.
  2. Register three listeners for notification.
  3. Use listenerCount().
  4. Pass the event name.
  5. 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:

  1. Receives user information.
  2. Emits a userRegistered event.
  3. Displays a welcome message.
  4. Sends a simulated email message.
  5. 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

  1. Import EventEmitter.
  2. Create an emitter object.
  3. Create a userRegistered event.
  4. Add the first listener to display a welcome message.
  5. Add the second listener to simulate sending an email.
  6. Add the third listener to record the registration.
  7. Create a user object.
  8. Emit the userRegistered event.
  9. Pass the user object to the event.
  10. 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 events module provides EventEmitter.
  • 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, or userRegistered.
  • 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.

Scroll to Top