Node Core Modules: EventEmitter, Streams, Buffers, os and process

Node.js and Express: Build a Back End API from Scratch · JavaScript and Node Core in Depth · 7 min read · Updated

Streams keep memory small

  1. A readable stream produces data in small chunks.
  2. A transform changes each chunk as it passes.
  3. A writable stream receives the chunks, and slows the sender if it is busy.
  4. pipeline connects them, passes errors and closes everything when done.

Node.js ships with a standard library that needs no installation, and several of its parts show up in every serious project. You have already used fs and path. This lesson adds the ones you meet next: events for letting parts of a program talk without knowing each other, streams for handling big data in small pieces, buffers for raw bytes, and the os and process modules for information about the machine and the running program. Express itself is built on them: a request is a readable stream, a response is a writable stream, and the server is an event emitter.

EventEmitter: announce, do not call

An EventEmitter lets one part of a program announce that something happened, while other parts listen. The sender does not need to know who listens. When an order is placed, the order code announces placed. The email code, the stock code and the analytics code each listen and do their own work. Adding a fourth listener needs no change to the order code. That is the idea behind event-driven design, and it returns in later lessons about queues and sockets.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Save each example below as its own file in the same folder and run it with node.
import { EventEmitter } from 'node:events';

class OrderService extends EventEmitter {
  place(item) {
    const order = { id: 1, item };
    this.emit('placed', order);   // tell anyone who is listening
    return order;
  }
}

const orders = new OrderService();
orders.on('placed', (order) => console.log('Email sent for', order.item));
orders.on('placed', (order) => console.log('Stock reduced for', order.item));
orders.once('placed', () => console.log('First order ever!'));

orders.place('Keyboard');
orders.place('Mouse');
console.log('Listeners:', orders.listenerCount('placed'));
Email sent for Keyboard
Stock reduced for Keyboard
First order ever!
Email sent for Mouse
Stock reduced for Mouse
Listeners: 2

Listeners run in the order you added them, and they run synchronously, one after another, when you call emit. A listener that throws stops the others, so keep listeners small and careful. The special event name error is different: if you emit error and nobody listens, Node throws and the process can crash. Always attach an error listener to emitters that can fail.

Streams: big data in small pieces

Reading a 2 GB file into memory with readFile could crash the server. A stream reads it in small chunks, passes each chunk along, and forgets it, so memory use stays small whatever the file size. There are four kinds: readable, writable, duplex and transform. A transform changes data as it passes, such as compressing or converting to upper case. pipeline connects streams, passes errors along, and closes everything properly. Prefer it to the older .pipe() method, which does not clean up when something fails.

import fs from 'node:fs';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import os from 'node:os';
import path from 'node:path';

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'streams-'));
const input = path.join(dir, 'in.txt');
const output = path.join(dir, 'out.txt');
fs.writeFileSync(input, 'hello\nstreams\nare\nuseful\n');

// A Transform changes each chunk as it passes through.
const upper = new Transform({
  transform(chunk, encoding, callback) {
    callback(null, chunk.toString().toUpperCase());
  },
});

// pipeline connects the streams and cleans up if one fails. Memory stays small for any file size.
await pipeline(fs.createReadStream(input), upper, fs.createWriteStream(output));
console.log(fs.readFileSync(output, 'utf8').trim().split('\n'));

// Buffers hold raw bytes.
const buffer = Buffer.from('Node', 'utf8');
console.log(buffer, buffer.length, buffer.toString('hex'), buffer.toString('base64'));
console.log(Buffer.concat([buffer, Buffer.from(' JS')]).toString());
fs.rmSync(dir, { recursive: true });
[ 'HELLO', 'STREAMS', 'ARE', 'USEFUL' ]
<Buffer 4e 6f 64 65> 4 4e6f6465 Tm9kZQ==
Node JS

In an Express route, fs.createReadStream(path).pipe(res) sends a large download without loading it, and req is a stream too, which is how upload libraries read big files in parts. Streams also have backpressure: if the receiver is slow, the sender is told to wait. pipeline handles this for you.

Buffers: raw bytes

A Buffer is a fixed block of bytes. Files, network packets, images and encrypted data are bytes, not text. The same buffer can be read as text with toString('utf8'), as hexadecimal with 'hex', or as base64 with 'base64'. You saw in the output that the text Node is four bytes, 4e 6f 64 65. Security code uses buffers constantly, for example to compare two secrets safely, and upload code uses them to check the first bytes of a file.

os and process

The os module tells you about the machine: the number of CPU cores, total and free memory, the platform. You use it to decide how many workers to start. The process object is the running program. process.argv holds the command-line words, process.env the environment variables, process.exitCode the result code, and process.on('exit') and process.on('SIGTERM') let you clean up when the program ends. A server should listen for SIGTERM, stop taking new requests, finish the current ones and then exit. Hosting tools send that signal when they restart your app.

import os from 'node:os';
import process from 'node:process';

console.log('Platform:', process.platform, '| Node:', process.version);
console.log('CPU cores:', os.cpus().length >= 1);
console.log('Total memory > 0:', os.totalmem() > 0);
console.log('Arguments after the script name:', process.argv.slice(2));
console.log('PORT from the environment:', process.env.PORT ?? '(not set)');

process.on('exit', (code) => console.log('Exiting with code', code));
process.exitCode = 0;
Platform: linux | Node: v22.23.4
CPU cores: true
Total memory > 0: true
Arguments after the script name: []
PORT from the environment: (not set)
Exiting with code 0

Your platform and version will differ. Two more things to remember: global objects such as process, Buffer, setTimeout, console and URL need no import, and globalThis is the standard name for the global object. Avoid putting your own data on it.

Your task

  1. Make the order service in the first example emit an error event for an empty item name and add a listener that logs it.
  2. Write a transform stream that turns each line into a numbered line, and use pipeline to process a text file.
  3. Run the os example with PORT=4000 node n17-os-process.js a b c and read the output.

How to check it worked

  • You can explain why pipeline is safer than .pipe().
  • You can name the four kinds of streams.
  • You can say why a large download should be streamed.

Frequently asked questions

When should I use streams instead of readFile?

When the data can be large or arrives over time, such as big files, uploads, downloads and logs. For small files, readFile is simpler.

What is backpressure?

A way for a slow receiver to tell a fast sender to pause, so memory does not fill up with data nobody has processed yet.

Why must I add an error listener to an EventEmitter?

An unhandled error event throws an exception, which can crash the whole process.

Practise with interview questions