bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Node.js/Core Modules
Node.js•Core Modules

Node.js Events

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');

Passing Arguments to Event Handlers

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

Handling Events Only Once

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

Error Handling

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'));

Always Handle Errors

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

Use Named Functions for Better Stack Traces

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

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);

Previous

Node.js URL Module

Next

Node.js Streams

This chapter

Overview
15

Lessons

209m

Read time

1. Node.js HTTP Module2. Node.js HTTPS Module3. Node.js File System Module4. Node.js Path Module5. Node.js OS Module6. Node.js URL Module7. Node.js Events8. Node.js Streams9. Node.js Buffer Module10. Node.js Crypto Module11. Node.js Timers Module12. Node.js DNS Module13. Node.js Assert Module14. Node.js Util Module15. Node.js Readline Module

On this page

Core Concepts of Events in Node.jsGetting Started with Events in Node.jsBasic ExampleEventEmitter ClassCreating an Event EmitterThe EventEmitter ObjectPassing Arguments to Event HandlersHandling Events Only OnceError HandlingAlways Handle ErrorsUse Named Functions for Better Stack TracesClean Up Listeners