Events and the EventEmitter
How Node lets one part of your program announce that something happened, and other parts react - without ever knowing about each other.
EventEmitter class is the small, powerful engine that makes this pattern available in your own code.
- create an
EventEmitterand register listeners withon()andonce(), - fire events with
emit()and pass data to listeners, - remove listeners and understand the special
errorevent, - use events to decouple parts of an application so they can change independently.
1. Thinking in events
You have already met events without naming them. When you wrote server.on('request', handler) for an HTTP server, or stream.on('data', chunk => ...) while reading a file, you were listening for events that Node emitted for you. This topic hands you the same machinery so your own objects can announce things.
In an event-driven design, the code that notices something happened does not call the code that should react. It just makes an announcement - "a user signed up", "a file finished downloading" - and walks away. Whoever cares has already subscribed. This is also called the publish/subscribe (pub-sub) or observer pattern.
Why bother? Because it keeps components loosely coupled. The part that creates a user should not need to know that we also send a welcome email, update analytics, and warm a cache. Bolting all of that into one function makes it long, fragile, and hard to test. Emitting a single userRegistered event lets each concern live in its own listener.