🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Node.js Notes
Topic #27

Events Module


Core Concepts of Events in Node.js

Every action on a computer is an event, like when a connection is made or a file is opened.

Objects in Node.js can fire events, like the readStream object fires events when opening and closing a file:

Example

let fs = require('fs');
let rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
  console.log('The file is open');
});

Getting Started with Events in Node.js

Node.js uses an event-driven architecture where objects called "emitters" emit named events that cause function objects ("listeners") to be called.

Basic Example

// Import the events module
const EventEmitter = require('events');

// Create an event emitter instance
const myEmitter = new EventEmitter();

// Register an event listener
myEmitter.on('greet', () => {
  console.log('Hello there!');
});

// Emit the event
myEmitter.emit('greet'); // Outputs: Hello there!

EventEmitter Class

The EventEmitter class is fundamental to Node.js's event-driven architecture.

It provides the ability to create and handle custom events.

Creating an Event Emitter

To use the EventEmitter, you need to create an instance of it:

let events = require('events');
let eventEmitter = new events.EventEmitter();

The EventEmitter Object

You can assign event handlers to your own events with the EventEmitter object.

In the example below we have created a function that will be executed when a "scream" event is fired.

To fire an event, use the emit() method.

Example

let events = require('events');
let eventEmitter = new events.EventEmitter();

//Create an event handler:
let myEventHandler = function () {
  console.log('I hear a scream!');
}

//Assign the event handler to an event:
eventEmitter.on('scream', myEventHandler);

//Fire the 'scream' event:
eventEmitter.emit('scream');

Common EventEmitter Patterns

1. Passing Arguments to Event Handlers

Example

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

// Emit event with arguments
emitter.on('userJoined', (username, userId) => {
  console.log(`${username} (${userId}) has joined the chat`);
});

emitter.emit('userJoined', 'JohnDoe', 42);
// Outputs: JohnDoe (42) has joined the chat

2. Handling Events Only Once

Example

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

// This listener will be called only once
emitter.once('connection', () => {
  console.log('First connection established');
});

emitter.emit('connection'); // This will trigger the listener
emitter.emit('connection'); // This won't trigger the listener again

3. Error Handling

Example

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

// Always handle 'error' events
emitter.on('error', (err) => {
  console.error('An error occurred:', err.message);
});

// This will trigger the error handler
emitter.emit('error', new Error('Something went wrong'));

Best Practices

1. Always Handle Errors

// Good practice: Always listen for 'error' events
myEmitter.on('error', (err) => {
  console.error('Error in event emitter:', err);
});

2. Use Named Functions for Better Stack Traces

// Instead of anonymous functions
function handleData(data) {
  console.log('Received data:', data);
}

myEmitter.on('data', handleData);

3. Clean Up Listeners

// Add a listener
const listener = () => console.log('Event occurred');
myEmitter.on('event', listener);

// Later, remove the listener when no longer needed
myEmitter.off('event', listener);

Want to go beyond the notes?

Join CodingNow 2.0's Node.js course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Events Module – FAQs

Quick answers about learning Events Module in Node.js.

This free note from CodingNow 2.0 explains Events Module in Node.js — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Node.js topic on CodingNow 2.0, including Events Module, is 100% free with no signup required.
With focused practice, most students grasp Events Module in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now