Nobody moves water from a tank to a bucket by lifting the tank. You attach a hose, and the water flows a bit at a time. If the water at the end has to pass through a slow filter, you turn the tap down so the filter doesn't overflow.
Node moves big data the same way. The tank is the big data, such as a file, and the bucket is where it goes. The hose is a stream: a way to process data a little at a time, one chunk (a small piece) at a time, without loading all of it into memory. Each bit of water that passes through the hose is one chunk. A chunk holds raw bytes, which are kept in a Buffer. Turning down the tap when the destination is slow is called backpressure.
Buffer: raw bytes
Files, network requests and images all arrive as bytes: numbers from 0 to 255. Node keeps them in a Buffer and shows them in hex:
const buf = Buffer.from("Hello Node", "utf-8");
console.log(buf); // <Buffer 48 65 6c 6c 6f 20 4e 6f 64 65>
console.log(buf.toString()); // Hello Node
console.log(buf.length); // 10
console.log(Buffer.from("Node").length); // 4
console.log(Buffer.from("café")); // <Buffer 63 61 66 c3 a9>
console.log(Buffer.from("café").length); // 5
Buffer.from(text, "utf-8")turns text into bytes with the UTF-8 encoding (the rules that give each letter its bytes).48is hex for the letterH,20for a space.buf.lengthcounts bytes, not letters. Plain characters (A-Z, digits, space) are 1 byte each, so"Hello Node"= 10 bytes and"Node"= 4.- UTF-8 uses more than 1 byte for other letters:
é= 2 bytes (c3 a9),€= 3 bytes. SoBuffer.from("café").lengthgives 5, while"café".length= 4. Buffer.alloc(1024)makes an empty 1,024-byte Buffer full of zeros.
Streams: reading piece by piece
notes-api has a route GET /notes/export that sends notes.csv, 5,000,000 bytes. With fs.readFile, all 5 MB go into memory first, then get sent. A hundred people downloading at the same time means 500 MB. With a stream, the file is read chunk by chunk:
const fs = require("node:fs");
const stream = fs.createReadStream("notes.csv");
let count = 0;
stream.on("data", (chunk) => {
count++;
console.log("Chunk " + count + ": " + chunk.length + " bytes");
});
stream.on("end", () => console.log("Done, " + count + " chunks"));
stream.on("error", (err) => console.error("Failed: " + err.message));
A stream uses the on pattern of EventEmitter: the "data" event happens for each new chunk, "end" when the whole file has been read, and "error" if something fails. The output:
Chunk 1: 65536 bytes
Chunk 2: 65536 bytes
...
Chunk 77: 19264 bytes
Done, 77 chunks
Each chunk is a 65,536-byte Buffer (64 KiB). That's createReadStream's default chunk size. So 5,000,000 bytes become 76 full chunks and one last chunk of 19,264 bytes. Only one chunk is in memory at a time.
Node has four kinds of stream:
- Readable: a source of data, such as a file being read.
- Writable: a destination for data, such as
res. - Duplex: a source and a destination, such as a socket (one network connection).
- Transform: it changes the data passing through, such as gzip compression (making data smaller).
pipe() and pipeline(): joining the hoses
pipe() connects a Readable to a Writable, so every chunk read is written right away:
app.get("/notes/export", (req, res) => {
res.setHeader("Content-Type", "text/csv");
fs.createReadStream("notes.csv").pipe(res);
});
In this route, res (the Express response) is a Writable, so each chunk of the file goes straight to the user.
pipeline() connects several streams in a row, and calls one callback when it finishes or fails. This example reads notes.csv, makes it smaller with gzip from zlib (the built-in module for compression), then writes the result to notes.csv.gz:
const { pipeline } = require("node:stream");
const zlib = require("node:zlib");
pipeline(fs.createReadStream("notes.csv"), zlib.createGzip(), fs.createWriteStream("notes.csv.gz"), (err) => {
console.log(err ? "Failed: " + err.message : "Done: notes.csv.gz");
});
If notes.csv doesn't exist, it prints Failed: ENOENT: no such file or directory, open 'notes.csv', and every stream in the pipeline is closed. With chained .pipe() calls (one .pipe() joined to the next .pipe()), you have to catch errors like that one in each stream, one by one. There is also a version of pipeline that uses a Promise, with no callback: take pipeline from require("node:stream/promises"), then write await pipeline(...) inside try/catch.
Backpressure: when the consumer is slower
The consumer is the side that receives the data. Reading from disk is fast, but sending to a user's phone over a weak signal is slow. If the reading stream (the Readable) keeps sending chunks, the queue of chunks waiting to be sent grows in memory. That's why writable.write(chunk) returns false as soon as its queue goes past the highWaterMark, the limit for the queue (64 KiB since Node 22, 16 KiB before). false is a sign to stop until the "drain" event happens, which is when the queue is empty again.
readable.on("data", (chunk) => {
if (!writable.write(chunk)) readable.pause(); // the queue is full: stop reading
});
writable.on("drain", () => readable.resume()); // the queue emptied: carry on
pipe() and pipeline() already do this for you. Web Streams (the browser's version of streams) use the same idea: highWaterMark sets how many chunks may queue, and controller.desiredSize tells how much room is left in the queue. In the Lab, try a slow consumer and watch the queue stop at the highWaterMark.
A letter cut at a chunk boundary
A chunk's boundary is set by a number of bytes, not letters, so one UTF-8 letter can be split. For a reading stream, highWaterMark also sets the chunk size. In this example, the file coffee.txt, which holds "latte at café", is read 13 bytes at a time:
fs.createReadStream("coffee.txt", { highWaterMark: 13 }).on("data", (chunk) => {
console.log(chunk, chunk.toString());
});
The output:
<Buffer 6c 61 74 74 65 20 61 74 20 63 61 66 c3> latte at caf�
<Buffer a9> �
c3 and a9 are split, and each is turned into text on its own. Half a letter can't be read, so � appears twice. The fix: give the stream the option { encoding: "utf8" }, so the stream turns the bytes into text. The bytes of an incomplete letter are held until the partner byte arrives. That gives "latte at caf", then "é". In the browser, new TextDecoder().decode(chunk, { stream: true }) does the same.
In the exercise: Buffer.from and pieces
The exercise measures "Hello Node" with Buffer.from(...).length. Then the 55-character text "This is example data that gets processed chunk by chunk" is cut into pieces of 10 characters, the way a stream cuts a file. The last piece may be shorter:
Buffer: "Hello Node" = 10 bytes
Data: "This is example data that gets processed chunk by chunk"
Chunk size: 10
Number of chunks: 6
Chunk 1: "This is ex"
Chunk 2: "ample data"
Chunk 3: " that gets"
Chunk 4: " processed"
Chunk 5: " chunk by "
Chunk 6: "chunk"
Buffer: "café" = 5 bytes
The last line measures "café" the same way: 5 bytes, not 4, because é takes 2 bytes.
⚠️ Swollen memory and broken letters
readFilefor a big file. All its content goes into memory on every request. For big files and downloads, usecreateReadStream(...).pipe(res).- Thinking
lengthis the number of letters.Buffer.lengthcounts bytes:"café"= 5. chunk.toString()per chunk. A multi-byte letter at a chunk boundary becomes�. Use{ encoding: "utf8" }orTextDecoderwith{ stream: true }.- Ignoring
falsefromwrite(). The queue swells until there is no memory left. Usepipe/pipeline, or wait for"drain".
TL;DR: A Buffer holds raw bytes (numbers from 0 to 255). Buffer.from("Hello Node") prints <Buffer 48 65 6c 6c 6f 20 4e 6f 64 65>, and its length is 10 bytes. "café" is 5 bytes because é = c3 a9. A stream processes data chunk by chunk (in pieces, 64 KiB for createReadStream) so memory doesn't fill up. There are four kinds of stream: Readable (a source), Writable (a destination), Duplex (both) and Transform (it changes the data passing through). pipe() connects a Readable to a Writable, and pipeline() also handles errors and closes all its streams. Backpressure means slowing the reader when the destination is slow. write() returns false when the queue passes the highWaterMark (the queue's limit), then you wait for the "drain" event, which happens when the queue is empty again. pipe() does this on its own. A multi-byte letter can be split at a chunk boundary, so read text with { encoding: "utf8" }, or in the browser with TextDecoder { stream: true }.
⚡ A Buffer counts bytes
Write:
const buf = Buffer.from("Hello Node", "utf-8");
console.log(buf.length); // 10
Guess first: é is not a plain letter from A to Z. What does Buffer.from("café").length give?
5, even though "café".length = 4. In UTF-8 (the rules that give each letter its bytes), é takes 2 bytes (c3 a9).
Meaning: A Buffer holds raw bytes: numbers from 0 to 255. Its length counts bytes, not letters. Plain letters, digits and spaces are 1 byte each.
⚡ A stream reads piece by piece
Write:
const stream = fs.createReadStream("notes.csv");
stream.on("data", (chunk) => {
console.log(chunk.length + " bytes");
});
Meaning: fs.readFile puts the whole file in memory first. A stream reads it in chunks (pieces) of 64 KiB, and the "data" event happens once for each chunk. So only one chunk sits in memory at a time.
⚡ Connect them with pipeline
Write:
pipeline(fs.createReadStream("notes.csv"), zlib.createGzip(), fs.createWriteStream("notes.csv.gz"), (err) => {
console.log(err ? "Failed: " + err.message : "Done: notes.csv.gz");
});
Meaning: pipeline connects streams from a source to a destination, like joining hoses. Here it reads notes.csv, makes it smaller with gzip from the zlib module, then writes it to notes.csv.gz. If one fails, every stream in it is closed and the error reaches the callback.