โš™๏ธ Node.js Core Concepts & Features
Estimated reading: 4 minutes 100 views

๐Ÿง  Node.js โ€“ Events, Event Loop & EventEmitter โ€“ Master Asynchronous Flow in Node.js


๐Ÿงฒ Introduction โ€“ What Are Events and EventEmitters in Node.js?

Node.js is built on non-blocking, asynchronous programming, and its event-driven architecture is the key to this model. The Event Loop allows Node.js to handle multiple operations without multi-threading, and the EventEmitter class lets developers implement their own custom event handling system.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How the Node.js event loop works
  • What EventEmitter is and how to use it
  • Real-world event-based examples
  • Best practices for building event-driven applications

๐Ÿ” What Is the Event Loop in Node.js?

The Event Loop is the engine that keeps Node.js non-blocking. It listens for events and executes callback functions when those events are triggered.

โœ… Key Concepts:

๐Ÿ”„ Phase๐Ÿ“˜ Description
TimersExecutes setTimeout() and setInterval() callbacks
Pending CallbacksI/O callbacks deferred to the next loop
Idle/PrepareInternal use
PollNew I/O events are polled
CheckExecutes setImmediate() callbacks
Close CallbacksExecutes close event callbacks (e.g., socket.on('close'))

๐Ÿ“Œ The event loop allows Node.js to pause and resume tasks without blocking the main thread.


๐Ÿ“ฃ What Is EventEmitter in Node.js?

The EventEmitter is a class in the events module that allows you to create, emit, and listen for custom events.

const EventEmitter = require('events');
const emitter = new EventEmitter();

๐Ÿงช Example โ€“ Basic EventEmitter Usage

const EventEmitter = require('events');
const emitter = new EventEmitter();

// Register an event listener
emitter.on('greet', (name) => {
  console.log(`Hello, ${name}!`);
});

// Emit the event
emitter.emit('greet', 'Node.js');

๐Ÿงช Output:

Hello, Node.js!

๐Ÿงฑ EventEmitter โ€“ Core Methods

MethodDescription
on(event, callback)Subscribes to an event
emit(event, data)Triggers the event with optional data
once(event, callback)Subscribes only for the first occurrence
removeListener()Removes a specific listener
removeAllListeners()Removes all listeners for an event

๐Ÿ“˜ Example โ€“ once() for One-Time Events

const emitter = new EventEmitter();

emitter.once('login', (user) => {
  console.log(`${user} logged in`);
});

emitter.emit('login', 'Vaibhav');
emitter.emit('login', 'AnotherUser'); // No output

๐Ÿงช Output:

Vaibhav logged in

๐Ÿ”„ Event Flow โ€“ How It All Works Together

  1. A module or function emits an event using emit().
  2. The event loop places it in the queue.
  3. Registered listener callbacks are executed.
  4. Non-blocking code continues immediately.

๐Ÿงช Real Use Case โ€“ File Watcher with Events

const fs = require('fs');
const EventEmitter = require('events');
const watcher = new EventEmitter();

fs.watch('myFile.txt', () => {
  watcher.emit('fileChanged');
});

watcher.on('fileChanged', () => {
  console.log('File was changed!');
});

๐Ÿงช Output (when file changes):

File was changed!

๐Ÿงฐ Best Practices โ€“ EventEmitter & Loop

โœ… Best Practice๐Ÿ’ก Why It Matters
Use once() for single-use eventsPrevents memory leaks and unnecessary triggers
Handle errors with on('error')Avoids crashing the application
Limit listener count using .setMaxListeners()Prevents memory warnings in large apps
Always clean up listenersPrevents memory leaks in long-running apps

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

Node.js uses an event-driven model where the Event Loop manages I/O and timers efficiently. The EventEmitter class helps you implement custom event-based architectures in your applications.

๐Ÿ” Key Takeaways:

  • The Event Loop runs behind the scenes to process async events
  • EventEmitter allows you to listen and react to events in code
  • Use .on(), .once(), and .emit() to manage event flow
  • Ideal for chat apps, file monitors, sockets, and real-time systems

โš™๏ธ Real-world relevance:
Widely used in server apps, WebSocket communication, logging systems, and automation scripts.


โ“FAQs โ€“ Node.js Events, Event Loop & EventEmitter


โ“ Is Node.js single-threaded or multi-threaded?
โœ… Node.js runs on a single thread, but uses the Event Loop to handle async operations non-blockingly.


โ“ Whatโ€™s the difference between setTimeout() and setImmediate()?
โœ… setTimeout() schedules after the specified delay, while setImmediate() runs in the next loop phase after I/O.


โ“ Can I create multiple EventEmitters?
โœ… Yes. Each instance of EventEmitter is independent and can manage its own events.


โ“ What happens if I emit an event with no listeners?
โœ… Nothing happens. Node.js will silently ignore it unless itโ€™s an 'error' event (which throws by default if unhandled).


โ“ How many listeners can I add to an EventEmitter?
โœ… By default, Node.js allows 10 listeners per event. Use emitter.setMaxListeners(n) to change the limit.


Share Now :
Share

๐Ÿง  Node.js โ€“ Events, Event Loop & EventEmitter

Or Copy Link

CONTENTS
Scroll to Top