bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Node.js/Core Modules
Node.js•Core Modules

Node.js Events

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Node.js Events?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ fs = require('fs');
3Order

Put the learning moves in the order that makes the concept easiest to apply.

EventEmitter Class
Getting Started with Events in Node.js
Core Concepts of Events in Node.js

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