Why streams, and Readable and Writable basics

Intermediate · 10 min

Why Node processes data in chunks, how Readable and Writable streams differ, and how to consume a stream with async iteration.

Before thisEvents and EventEmitterBuffers and binary dataThe file system with fs/promises

Codevolution · 10 min

Why streams, and Readable and Writable basics

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A stream hands you data in chunks as it arrives, so memory use depends on the chunk size, not on the size of the whole file or response.
  • `fs.readFile` loads the entire file into one Buffer before your code sees a byte. `fs.createReadStream` yields it in pieces, 64 KiB at a time by default.
  • Node has four stream types: Readable (a source), Writable (a destination), Duplex (both, independently), and Transform (a Duplex whose output is computed from its input).
  • `for await (const chunk of readable)` is the simplest way to consume a Readable. It handles end-of-stream and errors for you, and it applies backpressure automatically.
  • Streams are `EventEmitter`s: `data`, `end`, `error`, `finish` and `close` are the events you will see. An unhandled `error` event on a stream crashes the process.

The problem with “read it all, then use it”

Suppose a route returns a 1 GB export file:

import { readFile } from 'node:fs/promises';

const data = await readFile('export.csv'); // 1 GB Buffer, all at once
res.end(data);

Two things hurt. The process holds the whole gigabyte in memory per request, so ten concurrent downloads need ten gigabytes. And the client waits until the last byte is read from disk before it gets the first byte of the response.

A stream is a different contract. The source gives you a small piece, you handle it, then it gives you the next. Think of a water pipe versus a tanker truck: the truck must be completely filled before it leaves, while the pipe delivers from the first drop. The same idea covers network sockets, HTTP bodies, compression, and child process output, and Node’s core libraries expose all of them with one interface.

Four kinds of stream

  • Readable: a source of data. fs.createReadStream, an incoming HTTP request on the server, process.stdin.
  • Writable: a destination. fs.createWriteStream, an HTTP response, process.stdout.
  • Duplex: readable and writable at once, with the two sides independent. A TCP socket is the classic case.
  • Transform: a Duplex whose output is computed from its input, like zlib.createGzip(). The next lesson covers these.

All of them are EventEmitters. The events that matter: data and end on a Readable, finish on a Writable once everything has been flushed, close when the underlying resource is released, and error on any of them. As with every emitter, an error event with no listener throws and takes the process down.

Consuming a Readable

Every Readable is an async iterable. That is the form to reach for first:

import { createReadStream } from 'node:fs';

let chunks = 0;
for await (const chunk of createReadStream('big.txt', { encoding: 'utf8', highWaterMark: 16 })) {
  chunks++;
  console.log(JSON.stringify(chunk));
}
console.log('chunks', chunks);

Run against a 38-byte file, this prints three chunks, cut at 16 bytes with no regard for line boundaries:

"line 0\nline 1\nli"
"ne 2\nline 3\nline"
" 4\n"
chunks 3

Two details are worth noticing. The chunk boundaries are arbitrary, so never assume a chunk is a whole line, record or JSON value. And highWaterMark is the buffering threshold: for file streams it is also the read size. The default is 64 KiB. Without an encoding, each chunk is a Buffer; with one, you get strings, and Node takes care of multi-byte characters split across chunk boundaries.

The older style attaches listeners:

const stream = createReadStream('big.txt');
stream.on('data', (chunk) => { /* ... */ });
stream.on('end', () => console.log('done'));
stream.on('error', (err) => console.error(err));

It works, but you own all the wiring. The for await loop pulls one chunk at a time, ends when the stream ends, and throws if it errors, so ordinary try/catch covers failure.

Writing and creating streams

You can build a stream without a file. Readable.from() wraps any iterable, and a Writable needs only a write function that calls back when it is done with the chunk:

import { Readable, Writable } from 'node:stream';
import { once } from 'node:events';

for await (const c of Readable.from(['a', 'b', 'c'])) console.log(c);

const w = new Writable({
  write(chunk, encoding, callback) {
    console.log('got', chunk.toString());
    callback(); // signal "ready for the next chunk"
  },
});
w.write('hello');
w.end(' world');
await once(w, 'finish');
// got hello
// got  world

end() says no more data is coming, and finish fires after the last chunk has been processed. The callback is how a slow destination tells its producer to wait, which is the subject of the backpressure lesson.

What the video covers

Vishwas Gopinath’s episode is a short beginner introduction in his Node.js series, titled “Streams and Buffers”, from late 2022. By its title and series position it introduces what streams and buffers are and why chunked processing helps. I could not read a transcript, so I can’t vouch for which stream types or events it demonstrates. It predates the async-iteration-first style, so the for await approach, Readable.from, and the stream types taxonomy above come from this page. Pair it with the pipeline lesson next, since piping is where streams become useful.

Where this fits

Streams build on buffers and the event emitter. Next: transform streams and pipeline connect streams into processing chains. For the language feature underneath for await, see iterators and async generators in JavaScript.

Check yourself

  1. 01A server reads a 2 GB log file with `await readFile(path)` and sends it to each client. What goes wrong as traffic grows?

    Each request allocates a 2 GB Buffer before sending anything, so memory scales with file size times concurrent requests, and the first byte is delayed until the whole file is read. Piping `createReadStream(path)` into the response keeps memory at about one chunk per request and starts sending immediately.

  2. 02What is the difference between a Readable and a Duplex stream?

    A Readable only produces data, like a file opened for reading or an incoming HTTP request body. A Duplex has a readable side and a writable side that run independently, like a TCP socket. A Transform is a Duplex where the readable side is derived from what was written.

  3. 03Why is `for await (const chunk of stream)` usually preferable to a `stream.on('data', ...)` handler?

    The loop pulls one chunk at a time, so a slow loop body naturally slows the source, and it exits cleanly on `end` and throws on `error`, so a surrounding `try`/`catch` works. With `on('data')` you wire up `end` and `error` yourself, and nothing slows the source if your handler is slow.

  4. 04Does `readFile` ever beat a stream?

    Yes. For small files, such as config or a template, `readFile` is simpler and just as fast. Streams pay off when the data is large, unbounded, or arrives over time, like uploads, logs and network responses.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark