Skip to content

Events and the EventEmitter

Beginning of the lesson

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.

Big idea: Much of Node is event-driven. Instead of one function calling another directly, a component emits a named event, and any number of listeners react to it. The EventEmitter class is the small, powerful engine that makes this pattern available in your own code.
By the end of this topic you will be able to:
  • create an EventEmitter and register listeners with on() and once(),
  • fire events with emit() and pass data to listeners,
  • remove listeners and understand the special error event,
  • 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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers