Events, buffers, streams and files · core
EventEmitter
EventEmitter is Node's built-in publish/subscribe class: emit() calls every listener synchronously in the order they were added, and an 'error' event with no listener throws and can crash the process.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- on/addListener, once, off/removeListener; emit(name, ...args) returns true if there were listeners. Listeners run synchronously, in registration order.
- 'error' is special: emit('error', err) with no 'error' listener throws err.
- Streams, HTTP servers, sockets and child processes are EventEmitters. That is why you write on('data'), on('error'), on('close').
- More than 10 listeners for one event prints a MaxListenersExceededWarning. It usually means a leak, such as adding a listener per request and never removing it.
- events.once(emitter, name) returns a promise; events.on(emitter, name) gives an async iterator. Both accept an AbortSignal.
- Emitting inside a constructor is too early: listeners are attached after the constructor returns. The Node docs defer the emit with process.nextTick.
- emit does not await async listeners; a rejection inside one is not caught by emit (unless captureRejections is on), so catch errors inside async listeners.
The red pen
Common traps: mistake → fix
Mistake: emit is asynchronous
Fix: emit calls all listeners synchronously before it returns.
Mistake: Unhandled 'error' events are ignored
Fix: they throw; always listen for 'error' on streams and sockets.
Mistake: The listener-count warning is just noise
Fix: it usually points to a listener leak.
Easy to hard
Questions interviewers ask, easy to hard
- What is EventEmitter and where does Node use it?
- Is emit synchronous or asynchronous? Prove it with code.
- What happens when an 'error' event has no listener?
- How can EventEmitter cause a memory leak?
- Implement a small EventEmitter with on, once, off and emit.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.