Flash cards
Review the key moves
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.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ fs = require('fs');Put the learning moves in the order that makes the concept easiest to apply.
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 chatHandling 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 againError 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);