What are Events emitters in Node.js

What are Events emitters in Node.js
----------------------------------------------

In Node.js, event emitters are objects that help in implementing the observer pattern. They allow you to handle and respond to events in an asynchronous manner. The EventEmitter class is a core module in Node.js that provides the infrastructure for working with events.

Key concepts about EventEmitters:

Publisher-Subscriber Model:

EventEmitters follow a publisher-subscriber or observer pattern. They have the capability to emit named events that cause previously registered callbacks (subscribers) to be invoked.

Core Methods:

  1. on(eventName, listener) or addListener(eventName, listener): These methods are used to add a listener function to a specific event. Multiple listeners can be added to the same event.

  2. emit(eventName[, ...args]): This method triggers the specified event. It calls all listeners that are attached to that event with optional data passed as arguments.

  3. removeListener(eventName, listener): Removes a specific listener from an event.

  4. once(eventName, listener): Attaches a listener to an event that will be called only once, after which it's automatically removed.

const EventEmitter = require('events');

// Creating a custom emitter instance
const myEmitter = new EventEmitter();

// Registering a listener for an event
myEmitter.on('greet', (name) => {
  console.log(`Hello, ${name}!`);
});

// Emitting the 'greet' event
myEmitter.emit('greet', 'John'); // Output: Hello, John!

In this example, myEmitter is an instance of EventEmitter. The on() method attaches a listener to the 'greet' event, and when emit() is called with the 'greet' event name and the argument 'John', it triggers the listener and prints "Hello, John!".

Use Cases:

  • Handling HTTP requests in Node.js.
  • File system operations where events like 'fileOpen', 'fileClose', etc., can be emitted.
  • In custom modules to provide a way for other parts of the application to react to certain actions or changes.

EventEmitters in Node.js are fundamental for building asynchronous, event-driven applications, allowing better organization and handling of various events within your codebase.

 

Categories: Java Script Tags: #NodeJs, #ES6,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.