Explain it simply
Events and streams in plain language
An EventEmitter is an object that announces 'something just happened'. Interested code registers a listener under a name such as 'order-paid', and every emit runs those listeners. Servers, sockets and file streams are all built on EventEmitter, so you meet it everywhere in Node.js.
A stream is like a water pipe. Instead of pouring a whole tank into one cup at once, water flows through the pipe a little at a time. If the end of the pipe drinks slowly, the tap at the start has to slow down too; that is called backpressure.
Problem → Why → Solution
The problem: a 2 GB log file and a 512 MB container
On a developer laptop, a script that reads a log file with readFile and gzips it works fine, because the test file is 2 MB. In production the nightly log is 2 GB and runs inside a container limited to 512 MB. The whole file goes into one Buffer, a compressed copy is built in memory next to it, and the process dies with an out-of-memory error.
The fix moves to streams by chaining .pipe() calls. Memory is fine now, but on the night the disk fills up the write stream errors while the read stream stays open, and an incomplete .gz file is left behind that nobody notices.
import { readFile, writeFile } from 'node:fs/promises';
import { gzipSync } from 'node:zlib';
// Loads all 2 GB into memory, then builds a second buffer for the result.
const data = await readFile('access.log');
await writeFile('access.log.gz', gzipSync(data));
// "Fixed" with pipe(): memory is flat, but an error in any stage is not
// forwarded, the other streams stay open, and nothing is awaited.
// createReadStream('access.log').pipe(createGzip()).pipe(createWriteStream('out.gz'));Why both versions are wrong
The readFile version uses memory proportional to the file size, so it breaks on the day the data grows. The .pipe() version keeps memory flat, but it does not forward an error from one stage to the others, does not destroy the streams, and gives you no promise to await. pipeline() gives you chunk-by-chunk memory and error handling plus cleanup at the same time.
Core concept: emitters, chunks, buffer limits and pipeline
On an EventEmitter, on(name, fn) adds a listener, once removes itself after the first call, and off removes one. emit(name, ...args) calls the listeners synchronously in the order they were registered, so by the time emit returns they have all run. The name 'error' is special: emitting 'error' with no listener throws that error and can crash the process.
Streams are built on EventEmitter and move data in chunks. A Readable produces data (reading a file, an HTTP request body), a Writable consumes it (writing a file, an HTTP response), a Transform changes data in between (gzip, CSV parsing), and a Duplex is both readable and writable (a TCP socket). By default chunks are Buffers; with objectMode: true any JavaScript value can be a chunk.
Every stream has a buffer limit called highWaterMark, counted in bytes for byte streams and in objects in object mode. When a Writable's buffer reaches that limit, write() returns false, which means 'pause'. When the buffer empties it emits 'drain' and you may write again. Respecting that signal keeps memory near the buffer size instead of the file size.
Use pipeline() so you never handle these signals by hand. pipeline(source, ...transforms, destination), imported from node:stream/promises, respects backpressure, destroys every stream if any stage fails, and returns a promise that rejects with that error. The promise resolves only after the last stream has finished, so code after await pipeline(...) can safely assume the output file is complete. You can also pass an async generator function in a transform position.
| Stream type | Example in Node.js |
|---|---|
| Readable | fs.createReadStream, an HTTP request, Readable.from(iterable) |
| Writable | fs.createWriteStream, an HTTP response, process.stdout |
| Transform | zlib.createGzip(), your own filter or parser |
| Duplex | net.Socket (a TCP connection) |
- Readable produces one chunk
- Transform changes or drops it
- Full Writable buffer: write() false
- Source resumes only after 'drain'
- One error closes the whole chain
Memory is bounded by the buckets in the joints, so a 2 MB file and a 2 GB file use roughly the same amount.
General pattern
import { pipeline } from 'node:stream/promises';
emitter.on('event-name', (payload) => { /* react */ });
emitter.emit('event-name', payload);
const step = new Transform({
transform(chunk, encoding, done) { done(null, changed(chunk)); },
});
await pipeline(readableSource, step, writableDestination);Register listeners before you emit. Every transform must call done() exactly once per chunk: done(null, value) passes something on, plain done() drops the chunk, and done(error) fails the whole pipeline.
Worked example: filtering server errors out of a log
This example turns five access-log lines from a generator into a stream and keeps only lines whose status is 500 or higher. Each time an error line is found, an EventEmitter raises an alert, and the kept lines are collected by a Writable. If the generator produced fifty million lines instead of five, the code and its memory use would stay the same.
import { EventEmitter } from 'node:events';
import { Readable, Transform, Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
const alerts = new EventEmitter();
alerts.on('server-error', (line, count) => console.log(`alert #${count}: ${line}`));
function* accessLog() {
yield 'GET /home 200';
yield 'GET /cart 500';
yield 'POST /login 200';
yield 'GET /api/items 503';
yield 'GET /about 200';
}
let seen = 0;
let failures = 0;
const onlyFailures = new Transform({
objectMode: true,
transform(line, _encoding, done) {
seen += 1;
const status = Number(line.split(' ').at(-1));
if (status < 500) return done(); // drop the line, ask for the next one
failures += 1;
alerts.emit('server-error', line, failures);
done(null, `${line}\n`);
},
});
const saved = [];
const errorFile = new Writable({
objectMode: true,
write(chunk, _encoding, done) {
saved.push(chunk); // a real app would write to disk or a database here
done();
},
});
await pipeline(Readable.from(accessLog()), onlyFailures, errorFile);
console.log(`kept ${saved.length} of ${seen} lines`);Code breakdown
- Listener first
alerts.on('server-error', (line, count) => console.log(`alert #${count}: ${line}`));The listener is registered before the stream starts. Because emit is synchronous, each alert prints while its chunk is being processed.
- Source from an iterable
await pipeline(Readable.from(accessLog()), onlyFailures, errorFile);Readable.from turns the generator into an object-mode Readable. pipeline connects the three stages and returns a promise that settles when all of them finish or one fails.
- Drop a chunk
if (status < 500) return done(); // drop the line, ask for the next oneCalling done() with no value forwards nothing. Forgetting to call done() at all would stall the whole pipeline forever.
- Pass a chunk on
done(null, `${line}\n`);The first argument null means no error; the second is the value sent to the next stage.
- The consumer
saved.push(chunk); // a real app would write to disk or a database hereThe Writable's write method receives each chunk, and the next chunk is not delivered until done() is called; that is backpressure at its simplest.
alert #1: GET /cart 500
alert #2: GET /api/items 503
kept 2 of 5 linesSeeing backpressure with your own eyes
pipeline hides backpressure so well that you may never see it. The Writable below has a deliberately tiny highWaterMark of 8 bytes and takes 10 ms per write. After the second write, 10 bytes are buffered, so write() returns false.
import { Writable } from 'node:stream';
const slowDisk = new Writable({
highWaterMark: 8, // bytes buffered before write() asks you to wait
write(chunk, _encoding, done) {
setTimeout(done, 10); // pretend every write takes 10 ms
},
});
console.log(slowDisk.write('12345')); // 5 bytes buffered -> true
console.log(slowDisk.write('67890')); // 10 bytes buffered -> false: stop writing
slowDisk.once('drain', () => console.log('drain: safe to write again'));false does not mean the data was lost: the chunk was accepted into the buffer. But if you ignore false and keep writing in a loop, that buffer grows without limit. When you must call write() yourself, wait with await once(stream, 'drain') after a false, or better, turn the data into a Readable and use pipeline.
In real projects
Where events and streams show up in production
In every Express route, req and res are themselves streams, so large downloads, CSV exports and uploads can flow straight through a pipeline instead of being held fully in memory.
- Report exports: a database cursor (Readable) → a Transform that turns rows into CSV lines → createGzip() → the HTTP response. A million rows do not change the server's memory use.
- File uploads: the request body is streamed to object storage such as S3, and a byte-counting Transform errors once a size limit is passed, which makes pipeline abort the whole upload.
- Domain events: an order service emits 'order-paid' and the email, analytics and inventory modules each listen. Once you need more than one process you need a message queue, because EventEmitter works only inside a single process.
Common mistakes
Common mistakes with events and streams
Adding a listener on every request
Calling sharedEmitter.on(...) inside a request handler adds one more listener per request and never removes it. One event then runs the handler many times, memory creeps up, and after ten listeners Node prints MaxListenersExceededWarning. Register once at startup, use once, or remove the listener with off when the work is done.
Using .pipe() without error handling
In a.pipe(b).pipe(c), if b fails, a stays open, c never finishes, and the error does not travel along the chain. Without an 'error' listener on each stream the process may even crash. Await pipeline() and handle failure in one try/catch.
Forgetting done(), or calling it twice
If one if-branch returns without calling done(), the pipeline hangs silently forever. Calling done() twice raises ERR_MULTIPLE_CALLBACK. Check that every branch calls done() exactly once.
Best practices
Best practices
- Build every stream chain with pipeline() from node:stream/promises and await it.
- Prefer createReadStream over readFile when you do not know how big the data can get.
- Watch listener counts on long-lived emitters with listenerCount().
- To cancel a pipeline, pass an AbortController signal as pipeline(..., { signal }).
Mini challenge
Mini challenge: gzip a file and count its bytes
Create a log file in a temporary folder and gzip it with pipeline(). Put a Transform in the middle that counts bytes without changing them. Then decompress the .gz file, check that the byte counts match, and show how the pipeline fails for a file that does not exist.
- Use pipeline from node:stream/promises for both compressing and decompressing
- The byte-counting Transform must pass every chunk on unchanged
- Catch the missing-file error with try/catch and print error.code
- Delete the temporary folder in a finally block
import { createReadStream, createWriteStream } from 'node:fs';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { createGunzip, createGzip } from 'node:zlib';
function byteCounter() {
// TODO: return a Transform that adds chunk.length to a total
// and passes the chunk on; expose the total somehow
}
const dir = await mkdtemp(join(tmpdir(), 'gzip-demo-'));
// TODO: write a test log file into dir
try {
// TODO: source -> byteCounter -> gzip -> .gz file, then print the count
// TODO: .gz file -> gunzip -> second counter; compare the totals
// TODO: run a pipeline on a file that does not exist
} catch (error) {
// TODO: print error.code
} finally {
// TODO: remove dir
}Expected: Four lines: read 70000 bytes, compressed file is smaller: true, round trip bytes match: true, and pipeline failed: ENOENT.
Show hint
Inside transform(chunk, encoding, done), add chunk.length to a counter and call done(null, chunk). If you do not need the decompressed data, the last pipeline stage can be an async generator function that consumes the chunks with for await.
Show solution
import { createReadStream, createWriteStream } from 'node:fs';
import { mkdtemp, rm, stat, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { createGunzip, createGzip } from 'node:zlib';
function byteCounter() {
let bytes = 0;
const counter = new Transform({
transform(chunk, _encoding, done) {
bytes += chunk.length;
done(null, chunk); // pass the chunk through unchanged
},
});
counter.total = () => bytes;
return counter;
}
const dir = await mkdtemp(join(tmpdir(), 'gzip-demo-'));
const source = join(dir, 'access.log');
const target = join(dir, 'access.log.gz');
await writeFile(source, 'GET /home 200\n'.repeat(5000));
try {
const counter = byteCounter();
await pipeline(
createReadStream(source), counter, createGzip(), createWriteStream(target),
);
const { size } = await stat(target);
console.log(`read ${counter.total()} bytes`);
console.log(`compressed file is smaller: ${size < counter.total()}`);
const check = byteCounter();
const discard = async function* (chunks) {
for await (const _chunk of chunks); // consume without storing
};
await pipeline(createReadStream(target), createGunzip(), check, discard);
console.log(`round trip bytes match: ${check.total() === counter.total()}`);
const missing = join(dir, 'missing.log');
await pipeline(createReadStream(missing), createGzip(), createWriteStream(target));
} catch (error) {
console.log(`pipeline failed: ${error.code}`);
} finally {
await rm(dir, { recursive: true, force: true });
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- EventEmitter calls listeners synchronously in registration order, and an unhandled 'error' event throws.
- Streams move data in chunks, so memory depends on buffer size, not data size.
- write() returning false is backpressure: wait for 'drain'.
- Awaiting pipeline() handles backpressure, error propagation and cleanup in one place.
Streams — Node.js