What is the Observer pattern and how does it relate to Node.js EventEmitter?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

Answer

The Observer pattern (also called Publish-Subscribe or Pub-Sub) is a behavioral design pattern where an object (subject/publisher) maintains a list of dependents (observers/listeners) and notifies them automatically when its state changes. Node.js's EventEmitter is a direct implementation of this pattern. The EventEmitter is the publisher; emitter.on("event", listener) registers observers; emitter.emit("event", data) notifies all observers synchronously. This is the backbone of Node.js's entire architecture — HTTP servers, streams, file watchers, and TCP sockets all extend EventEmitter. Advantages: loose coupling (publisher doesn't know who is listening), extensibility (add behavior without modifying the publisher), supports multiple handlers for the same event. Considerations: (1) Memory leaks from forgotten listeners — use once() for one-time handlers, off() to clean up; (2) Default listener limit is 10 per event (warnings in console) — increase with emitter.setMaxListeners(n); (3) Errors emitted via emit("error", err) will crash the process if no error listener is registered — always add one: emitter.on("error", handler).

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Node.js codebase.