EventEmitter
EventEmitter is a core concept in Node.js, used to handle and trigger custom events. It is part of the events module, which allows you to build asynchronous event-driven systems.
Key Concepts:
Emit Events: Emitters generate named events that cause functions ("listeners") to be called.
Listeners: Functions that respond to events. You can register multiple listeners for a single event.
Basic Usage:
javascript
Copy code
const EventEmitter = require('events');
// Create an emitter instance
const myEmitter = new EventEmitter();
// Register a listener for the 'event' event
myEmitter.on('event', () => {
console.log('An event occurred!');
});
// Emit the 'event'
myEmitter.emit('event'); // Output: An event occurred!
Common Methods:
on(event, listener): Registers a listener for the event.
emit(event, [...args]): Triggers the event with optional arguments.
once(event, listener): Registers a one-time listener for the event.
removeListener(event, listener): Removes a specific listener for the event.
Use Cases:
Custom event systems.
Frameworks like Express.js use it for handling HTTP requests (via middleware).
Streams in Node.js also use EventEmitter to handle data, error, and end events.
Top comments (0)