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.
Node.js provides the EventEmitter class through the
built-in events module. We can use it to create our
own events.
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', function () {
console.log('Hello! Welcome to Node.js.');
});
emitter.emit('greet');
Hello! Welcome to Node.js.
on() registers a listener, while
emit() triggers the 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');
A new message arrived.
A new message arrived.
on() adds an event listener.emit() triggers the named event.
You can pass values to an event using emit().
These values become arguments of the listener function.
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');
Student Name: Rahul
Course: Node.js
The values 'Rahul' and 'Node.js'
are passed to the listener in the same order.
The once() method registers a listener that runs only
the first time the specified event is emitted.
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');
Welcome to our course!
once() is useful when an action should happen
only once, such as initial setup or a one-time notification.
We can remove a listener using off() or
removeListener(). To remove a specific listener,
keep a reference to the original function.
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');
Event received.
The second emit() produces no output because
the listener has been removed.
We can create our own class by extending EventEmitter.
This is useful for organizing events in larger applications.
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');
Amit has registered.
Welcome, Amit!
Here, Student extends
EventEmitter. Its register()
method emits a custom registered event.
The special error event needs attention. If an
EventEmitter emits error and no error listener is
registered, Node.js normally throws the error.
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'));
Error handled: Something went wrong
error listener when
using EventEmitter operations that may emit this event.
Handling this event does not automatically catch every
unrelated error or rejected promise.
| 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. |
removeAllListeners() on an
emitter shared with other parts of an application unless you intend
to remove their listeners too.
This example emits an event when a student enrolls in a course and displays a confirmation message.
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');
Priya enrolled in Full Stack Development
Rohit enrolled in Node.js
Save the code as course.js and run it with
node course.js.
events module.Library extending EventEmitter.issueBook(studentName, bookName).bookIssued event with the student's name and book name.once() for a separate welcome event.Challenge: Remove a listener and check whether it still runs after the event is emitted again.
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?