Lesson 16 of 50 – EventEmitter
32% Completed
32%

Node.js EventEmitter

The EventEmitter class is used to create and handle custom events in Node.js. We can register event listeners, emit events, pass data to listeners, and execute a listener only once.

Remember: An event is something that happens. An event listener is a function that runs when that event occurs. EventEmitter helps us connect these two things.

1. What Is EventEmitter?

Node.js provides the EventEmitter class through the built-in events module. We can use it to create our own events.

Example: Creating an EventEmitter
const EventEmitter = require('events');

const emitter = new EventEmitter();

emitter.on('greet', function () {
    console.log('Hello! Welcome to Node.js.');
});

emitter.emit('greet');
Output:
Hello! Welcome to Node.js.

on() registers a listener, while emit() triggers the event.

2. Understanding on() and emit()

Register and Trigger an Event
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('message', function () {
    console.log('A new message arrived.');
});

emitter.emit('message');
emitter.emit('message');
Output:
A new message arrived.
A new message arrived.
  • on() adds an event listener.
  • emit() triggers the named event.
  • The listener runs each time this event is emitted.

3. Passing Data with Events

You can pass values to an event using emit(). These values become arguments of the listener function.

Example: Passing Student Details
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('student', function (name, course) {
    console.log('Student Name:', name);
    console.log('Course:', course);
});

emitter.emit('student', 'Rahul', 'Node.js');
Output:
Student Name: Rahul
Course: Node.js

The values 'Rahul' and 'Node.js' are passed to the listener in the same order.

4. Using once()

The once() method registers a listener that runs only the first time the specified event is emitted.

Example: Run Only Once
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.once('welcome', function () {
    console.log('Welcome to our course!');
});

emitter.emit('welcome');
emitter.emit('welcome');
emitter.emit('welcome');
Output:
Welcome to our course!
once() is useful when an action should happen only once, such as initial setup or a one-time notification.

5. Removing an Event Listener

We can remove a listener using off() or removeListener(). To remove a specific listener, keep a reference to the original function.

Example: Using off()
const EventEmitter = require('events');
const emitter = new EventEmitter();

function showMessage() {
    console.log('Event received.');
}

emitter.on('notice', showMessage);

emitter.emit('notice');

emitter.off('notice', showMessage);

emitter.emit('notice');
Output:
Event received.

The second emit() produces no output because the listener has been removed.

6. Creating a Custom EventEmitter Class

We can create our own class by extending EventEmitter. This is useful for organizing events in larger applications.

Example: Student Registration
const EventEmitter = require('events');

class Student extends EventEmitter {
    register(name) {
        console.log(name + ' has registered.');

        this.emit('registered', name);
    }
}

const student = new Student();

student.on('registered', function (name) {
    console.log('Welcome, ' + name + '!');
});

student.register('Amit');
Output:
Amit has registered.
Welcome, Amit!

Here, Student extends EventEmitter. Its register() method emits a custom registered event.

7. Handling the error Event

The special error event needs attention. If an EventEmitter emits error and no error listener is registered, Node.js normally throws the error.

Example: Listening for Errors
const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.on('error', function (err) {
    console.log('Error handled:', err.message);
});

emitter.emit('error', new Error('Something went wrong'));
Output:
Error handled: Something went wrong
Register an appropriate error listener when using EventEmitter operations that may emit this event. Handling this event does not automatically catch every unrelated error or rejected promise.

8. Useful EventEmitter Methods

Method Purpose
on(event, listener) Registers a listener that can run multiple times.
emit(event, ...args) Triggers an event and passes optional arguments.
once(event, listener) Registers a listener that runs at most once.
off(event, listener) Removes a specific listener.
removeListener(event, listener) Removes a specific listener; an alternative to off().
removeAllListeners(event) Removes all listeners for an event, or all events if omitted.
listenerCount(event) Returns the number of listeners for an event.
Best practice: Remove listeners when they are no longer needed. Avoid using removeAllListeners() on an emitter shared with other parts of an application unless you intend to remove their listeners too.

9. Practical Example: Course Enrollment

This example emits an event when a student enrolls in a course and displays a confirmation message.

Complete Program
const EventEmitter = require('events');

class Course extends EventEmitter {
    enroll(studentName, courseName) {
        this.emit('enrollment', studentName, courseName);
    }
}

const course = new Course();

course.on('enrollment', function (student, courseName) {
    console.log(student + ' enrolled in ' + courseName);
});

course.enroll('Priya', 'Full Stack Development');
course.enroll('Rohit', 'Node.js');
Output:
Priya enrolled in Full Stack Development
Rohit enrolled in Node.js

Save the code as course.js and run it with node course.js.

📝 Practical Assignment

Practice Task
Create a Node.js program that:
  1. Imports the events module.
  2. Creates a class named Library extending EventEmitter.
  3. Creates a method named issueBook(studentName, bookName).
  4. Emits a bookIssued event with the student's name and book name.
  5. Displays a message when a book is issued.
  6. Uses once() for a separate welcome event.

Challenge: Remove a listener and check whether it still runs after the event is emitted again.


🧠 Quiz – EventEmitter

Choose the correct answer for each question.

1. Which module provides EventEmitter?

2. Which method triggers an event?

3. Which method registers a listener to run only once?