What does the emit() method do?
1. What emit() does
The
.emit(eventName, [...args])method fires an event namedeventNameand calls all handlers (listeners) that were subscribed to it via.on()or.once().
Example:
javascript
const EventEmitter = require('events');
const emitter = new EventEmitter();
// Subscribe
emitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
// Fire the event
emitter.emit('greet', 'Tim');Output:
javascript
Hello, Tim!What happened:
.emit('greet', 'Tim')creates thegreetevent;- Node.js finds all listeners for
greet; - it calls each of them, passing
'Tim'as an argument; - if there are no listeners, nothing happens.
2. Syntax
javascript
emitter.emit(eventName[, ...args])eventName, a string (the event's name);...args, any values that will be passed to the listeners.
3. How it works under the hood
When .emit() is called:
- Node.js looks up its internal map of listeners (
_events); - checks whether there are listeners for
eventName; - if there are, it calls them in registration order (
.on()->.once()); - if it's a
.once()listener, it's removed after the call; - if the
'error'event is emitted with no listener, an exception is thrown and the process terminates.
Special behavior for 'error'
If you call:
javascript
emitter.emit('error', new Error('Something went wrong'));and there's no 'error' listener, Node.js will:
- throw an error (
Uncaught Error); - terminate the process.
That's why it's good practice to always add an 'error' handler:
javascript
emitter.on('error', (err) => {
console.error('Error caught:', err.message);
});4. Return value
.emit() returns:
true, if the event has at least one listener;false, if it has none.
javascript
console.log(emitter.emit('greet')); // true
console.log(emitter.emit('unknown')); // false5. Example with several listeners
javascript
emitter.on('update', () => console.log('Update received'));
emitter.on('update', () => console.log('Data processed'));
emitter.emit('update');Output:
javascript
Update received
Data processed6. Example with arguments
javascript
emitter.on('sum', (a, b) => {
console.log('Sum =', a + b);
});
emitter.emit('sum', 3, 7);Output:
javascript
Sum = 10Summary
The
.emit()method:
- fires an event on an
EventEmitterobject;- calls all handlers subscribed via
.on()and.once();- can pass arguments to the listeners;
- returns
trueif there are listeners, andfalseif there aren't.This is the main way to "tell" the system that something happened, so other parts of the code can react.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.