DEV Community

Anjali Gurjar
Anjali Gurjar

Posted on

Event Emitter

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.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay