What is Event Emitter in Node.js: Simple Explanation and Example
EventEmitter is a class that allows objects to emit named events and register functions called listeners to respond to those events. It helps manage asynchronous actions by signaling when something happens, like a message arriving or a task completing.How It Works
Think of an EventEmitter like a radio station that broadcasts signals (events) to listeners. When the station sends out a signal, all radios tuned in (listeners) receive it and react accordingly. In Node.js, an object that inherits from EventEmitter can send out named events, and other parts of your program can listen and respond to those events.
This system helps separate the code that triggers an action from the code that reacts to it, making programs easier to organize and handle asynchronous tasks like reading files, receiving data, or user interactions.
Example
This example shows how to create an event emitter, listen for an event named greet, and emit it with a message.
import { EventEmitter } from 'events'; const emitter = new EventEmitter(); // Register a listener for the 'greet' event emitter.on('greet', (name) => { console.log(`Hello, ${name}!`); }); // Emit the 'greet' event with a name emitter.emit('greet', 'Alice');
When to Use
Use EventEmitter when you want to handle events or signals in your program without blocking other code. It is perfect for situations where actions happen at unpredictable times, like:
- Responding to user input or clicks
- Handling data arriving from a network or file
- Coordinating multiple asynchronous tasks
- Building custom modules that notify others when something happens
This pattern helps keep your code clean and responsive.
Key Points
- EventEmitter is a core Node.js class for event-driven programming.
- It lets you register listeners for named events and emit those events with data.
- Listeners run when their event is emitted, enabling asynchronous communication.
- It helps organize code that reacts to actions happening over time.