Node.js › Events & EventEmitter
How does the 'once' method differ from 'on' when subscribing to an EventEmitter's events, and when would you use it?
IntermediateAnswer
.once() registers a listener that automatically removes itself after being invoked exactly one time, whereas .on() keeps a listener attached indefinitely, firing every time the event is emitted -- .once() is appropriate for events that logically only need to be handled a single time per instance (like an initial 'ready' or 'connect' event), avoiding both the need to manually remove the listener afterward and any risk of it firing again unexpectedly on a subsequent emission.
const server = net.createServer();
server.once('listening', () => {
console.log('Server is now listening (this only logs once, even if listening fires again later)');
});
server.on('connection', (socket) => {
console.log('New connection'); // fires every single time, as expected for repeated connections
});Real-world example A database client class uses .once('connect', ...) to run one-time initialization logic exactly when the connection is first established, while using .on('query', ...) for logging every individual query, since queries are expected to happen repeatedly throughout the connection's lifetime unlike the single initial connection event.