Skip to main content

Events and Streams

The EventEmitter Class

Much of the Node.js core architecture is logically built around an idiomatic asynchronous event-driven structure natively called the EventEmitter.

Certain objects predictably emit named triggers, causing specifically registered listener functions to execute globally.

import EventEmitter from 'node:events';

class TicketManager extends EventEmitter {}

const myManager = new TicketManager();

// 1. Registering the Listener securely
myManager.on('ticketPurchased', (userEmail) => {
console.log(`Sending explicit confirmation email to: ${userEmail}`);
});

// 2. Triggering the Event globally
myManager.emit('ticketPurchased', 'alice@test.com');

Data Streams

When you utilize fs.readFile to load a massive 5GB structural video file, Node attempts to explicitly load all 5 GB dynamically directly into your local RAM instantly smoothly. This will predictably crash the Node server Native Process cleanly.

Instead of loading the entire heavy payload simultaneously correctly, Node utilizes Streams to systematically pull specific "Chunks" of data securely, processing them incrementally cleanly.

import fs from 'node:fs';

const readableStream = fs.createReadStream('./massive-movie.mp4');

// The 'data' event natively fires continuously whenever a new partial chunk loads natively!
readableStream.on('data', (chunk) => {
console.log(`Received explicit data chunk of size: ${chunk.length} bytes`);
});

// The 'end' event fires locally firmly when the entire file finishes effectively downloading cleanly
readableStream.on('end', () => {
console.log('Finished streaming the entire file natively!');
});