What does once() do?
1. What once() does
The
.once(eventName, listener)method registers an event handler that will run only once, then remove itself automatically.
After the event fires the first time, the listener won't be called again, even if an event with the same name fires again.
Example:
javascript
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.once('connect', () => {
console.log('Connection established!');
});
emitter.emit('connect'); // fires
emitter.emit('connect'); // won't fire againOutput:
javascript
Connection established!2. What on() does
The
.on(eventName, listener)method registers a permanent event handler. It will be called every time the event fires.
Example:
javascript
emitter.on('data', () => {
console.log('Data received');
});
emitter.emit('data'); // fires
emitter.emit('data'); // fires againOutput:
javascript
Data received
Data received3. The key difference between once() and on()
| Characteristic | on() | once() |
|---|---|---|
| Number of firings | Unlimited (every emit()) | Only once |
| Manual listener removal needed? | Yes, if needed (off()) | No, removed automatically |
| Typical use cases | Repeating events (e.g. data, message) | One-time events (connect, ready, close, finish) |
| Memory impact | Listener stays around | Listener is removed after the call |
4. Why once() is useful
- Avoids memory leaks, the listener is removed automatically.
- Convenient for initialization, e.g. a server's
readyevent or a stream'sopenevent. - Simplifies logic, no need to call
.off()manually.
5. A real-world example
For instance, on an HTTP server:
javascript
const http = require('http');
const server = http.createServer();
server.once('listening', () => {
console.log('Server started!');
});
server.listen(3000);The 'listening' event should happen once,
so .once() is a perfect fit.
Summary
on()adds a permanent listener that's called every timeemit()fires.once()adds a one-time listener that's removed after its first call.Recommended usage:
- use
on()for repeating events (data,message,update);- use
once()for one-time events (connect,ready,close,init).
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.