Node.js has a built-in events module that allows us to work with event-driven programming. Events in Node.js are similar to browser events but are used in a server-side environment.
EventEmitter
class is used to create and handle custom events.Example: Using Events in Node.js
const EventEmitter = require('events');
const event = new EventEmitter();
// Creating an event listener
event.on('greet', () => {
console.log('Hello! Welcome to Node.js Events.');
});
// Emitting (triggering) the event
event.emit('greet');
Node.js Event Loop
The Event Loop is the heart of Node.js. It allows Node.js to handle asynchronous operations without blocking the main thread.
📌 How It Works:
setTimeout
, I/O operations).process.nextTick()
.