Events & EventEmitter in nodejs
medium · Node.js — Server-side JavaScript
In Node.js, much of the core architecture is event-driven . This means that certain objects (called "emitters") emit named events that cause functions (called "listeners") to be executed. This is handled by the built-in events module. In Node.js, much of the core architecture is event-driven . This means that certain objects (called "emitters") emit named events that cause functions (called "listeners") to be executed. This is handled by the built-in events module. 1. What is an EventEmitter? The EventEmitter class is the key to this pattern. It allows you to create an object that "speaks" to other parts of your application by broadcasting messages. Emit: To "shout" or broadcast that something has happened (e.g., user-logged-in ). Listen (on): To "wait" for a specific shout and perform an action when it occurs. 2. Basic Implementation To use it, you must require the events module and create an instance of the EventEmitter class. const EventEmitter = require('events'); // Create an instance const myEmitter = new EventEmitter(); // 1. Define a Listener (The "Subscriber") myEmitter.on('order-placed', (orderId, customer) => { console.log(`Processing order #${orderId} for ${customer}...`); }); // 2. Emit the Event (The "Publisher") myEmitter.emit('order-placed', 101, 'Tharun'); 3. Key API Methods Method Description .on(eventName, listener) Adds a listener function for the specified event. It triggers every time the event is emitted. .once(eventName, listener) Adds a listener that triggers only once . After it runs, it is automatically removed. .emit(eventName, [...args]) Synchronously calls each of the listeners registered for the event, passing the supplied arguments. .off() or .removeListener() Removes a specific listener from an event to prevent memory leaks. .removeAllListeners() Clears all listeners for a specific event or all events on that emitter. 4. Error Events In Node.js, the 'error' event is special. If an EventEmitter emits an 'error' and there is no listener registered for it, the Node.js process will crash and print a stack trace. Best Practice: Always register a listener for the 'error' event. myEmitter.on('error', (err) => { console.error('Whoops! There was an error:', err.message); }); myEmitter.emit('error', new Error('Connection Failed')); 5. Real-World Usage: Extending EventEmitter In professional development, you rarely use the myEmitter instance directly. Instead, you create a class that inherits from EventEmitter . This is how built-in modules like http.Server and fs.ReadStream work. const EventEmitter = require('events'); class JobPortal extends EventEmitter { publishJob(title) { console.log(`New Job Posted: ${title}`); this.emit('newJob', title); } } const careeroza = new JobPortal(); // Someone "subscribes" to new job notifications careeroza.on('newJob', (title) => { console.log(`Sending email notification for: ${title}`); }); careeroza.publishJob('MERN Stack Developer'); 6. Synchronous vs. Asynchronous By default, EventEmitter treats all listeners synchronously in the order they were registered. This ensures proper sequencing of events. However, if you need a listener to behave asynchronously, you can wrap its logic in setImmediate() or process.nextTick() . Summary: The EventEmitter is the backbone of Node.js. It allows for a decoupled architecture where the object triggering the action (the Publisher) doesn't need to know which functions are responding to it (the Subscribers).