Event in nodejs
Created on: Aug 15, 2024
In Node.js, an EventEmitter is a core feature that allows objects to emit events and handle them. It is part of the events
module, which is built into Node.js.
All objects that emit events are instances of the EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used.
const EventEmitter = require("node:events"); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on("greet", (name) => { console.log(`Hello, ${name}!`); }); myEmitter.emit("greet", "John Doe");
Run above program using below command
node SimpleEvent.js
Output
Hello, John Doe!
Handling event once
const EventEmitter = require("node:events"); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); let m = 0; myEmitter.once("event", () => { console.log(++m); }); myEmitter.emit("event"); // Prints: 1 myEmitter.emit("event"); // Ignored
An error event can be attached using below
myEmitter.on("error", (err) => { console.error("An error occurred:", err); });
And event can be turned off using below command
myEmitter.on('error', (err) => { console.error('An error occurred:', err); });
Attaching multiple listeners
const EventEmitter = require("node:events"); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); const greetListener1 = (name) => { console.log(`Listener 1: Hello, ${name}!`); }; const greetListener2 = (name) => { console.log(`Listener 2: Hello, ${name}!`); }; const greetListener3 = (name) => { console.log(`Listener 3: Hello, ${name}!`); }; const greetListener4 = (name) => { console.log(`Listener 4: Hello, ${name}!`); }; myEmitter.on("error", (err) => { console.error("An error occurred:", err); }); myEmitter.on("greet", greetListener1); myEmitter.on("greet", greetListener2); myEmitter.on("greet", greetListener3); myEmitter.on("greet", greetListener4); myEmitter.emit("greet", "John Doe"); const listeners = myEmitter.listeners("greet"); console.log(listeners.length);
Benefit of event
- Asynchronous and Non-Blocking Architecture Events allow Node.js applications to handle multiple operations concurrently without blocking the main thread.
- Events promote loose coupling between different parts of an application.
- Events are at the core of event-driven architecture (EDA), where the flow of the application is determined by events.
- Events are ideal for building real-time systems where timely updates are crucial. Whether it's a chat application, live sports scores, or stock market updates, events ensure that data is processed and delivered as soon as it is available.
Internal working
- The
EventEmitter
class is the foundation for handling events in Node.js. It provides methods like on(), emit(), once(), removeListener(), and others that allow developers to interact with the event system. - Storing Listeners: When you register a listener for an event using on() or once(), the EventEmitter stores this listener in an internal data structure. Typically, this is a JavaScript object where the keys are the event names and the values are arrays of listener functions.
- When you emit an event using the emit() method, the EventEmitter looks up the event name in its internal data structure. If listeners are registered for that event, they are executed in the order they were added.