What does the on() method do?
1. What on() does
.on(eventName, listener)registers a handler (function) for a given event. Every time an event namedeventNamefires via.emit(), every handler added through.on()is called in registration order.
Example:
javascript
const EventEmitter = require('events');
const emitter = new EventEmitter();
// Subscribe
emitter.on('message', (text) => {
console.log('Message received:', text);
});
// Fire the event
emitter.emit('message', 'Hello, Node.js!');Output:
javascript
Message received: Hello, Node.js!2. Syntax
javascript
emitter.on(eventName, listener)eventName, a string, the event's name (e.g.'data','error','end').listener, the handler function that gets called when the event occurs.
3. Example with several listeners
javascript
emitter.on('update', () => console.log('First listener'));
emitter.on('update', () => console.log('Second listener'));
emitter.emit('update');Output:
javascript
First listener
Second listener4. How on() differs from addListener()
| Method | Difference |
|---|---|
.on() | The modern, more readable method name |
.addListener() | The old name, kept for compatibility (works exactly the same way) |
In fact, on() is an alias (synonym) for addListener():
javascript
EventEmitter.prototype.on === EventEmitter.prototype.addListener // trueThat is:
javascript
emitter.on('event', listener);and
javascript
emitter.addListener('event', listener);do exactly the same thing.
5. Which one to use, and when
- Use
.on(), it's the modern, familiar choice (used throughout the official docs and every example). .addListener()remains for backward compatibility with earlier Node.js versions.
Summary
on()subscribes a function to an event (called on everyemit()).addListener()is a completely identical method, just an older name. There is no difference in behavior at all, they're aliases for the same method.
.on()is recommended as the modern standard.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.