Streams & Buffers
Readable, writable, transform streams, piping, and binary data.
Buffers: raw bytes in JavaScript
JavaScript strings hold text, but files, network packets, and images are bytes. Node's Buffer is a fixed-size chunk of raw memory for exactly that. You met Buffers already — fs.readFile without an encoding returns one.
Creating Buffers:
Buffer.from("text", "utf8")— encode a string into bytesBuffer.from([72, 105])— from an array of byte values (0–255)Buffer.alloc(10)— 10 zero-filled bytes
A Buffer has a length in bytes — not characters. Multi-byte characters (like emoji or accented letters) occupy several bytes each in UTF-8.
const ascii = Buffer.from("Hi");
console.log(ascii); // <Buffer 48 69>
console.log(ascii.length); // 2 bytes
const emoji = Buffer.from("h\u00e9!"); // "hé!"
console.log("string length:", "h\u00e9!".length); // 3 characters
console.log("buffer length:", emoji.length); // 4 bytes (é = 2 bytes)
console.log(Buffer.alloc(4)); // <Buffer 00 00 00 00>
console.log(Buffer.from([72, 105]).toString()); // "Hi"Encodings: utf8, hex, base64
An encoding is a rule for translating between bytes and text. buf.toString(encoding) decodes bytes to a string; Buffer.from(str, encoding) goes the other way.
utf8— the default; how virtually all modern text is storedhex— two hexadecimal characters per byte; used for hashes and IDsbase64— packs bytes into 64 printable characters; used to embed binary data in JSON, URLs, and emails
Round-tripping through an encoding is lossless as long as you use the same encoding both ways.
const buf = Buffer.from("Node.js");
console.log("utf8: ", buf.toString("utf8"));
console.log("hex: ", buf.toString("hex"));
console.log("base64:", buf.toString("base64"));
// Round trip through base64:
const encoded = buf.toString("base64");
const decoded = Buffer.from(encoded, "base64").toString("utf8");
console.log("round-tripped:", decoded);Streams: processing data piece by piece
Reading a 4 GB log file with readFile loads 4 GB into memory. A stream instead delivers the file as a series of small chunks (Buffers, typically 64 KB), which you process as they arrive. Memory use stays tiny and the first chunk arrives immediately.
Node has four stream types:
- Readable — a source of chunks (file reads, HTTP request bodies)
- Writable — a destination (file writes, HTTP responses)
- Duplex — both at once (TCP sockets)
- Transform — a duplex that modifies data passing through (gzip, encryption)
Streams are EventEmitters: readables emit data, end, and error; writables emit finish, drain, and error.
const fs = require("fs");
const stream = fs.createReadStream("./big.log", {
encoding: "utf8",
highWaterMark: 64 * 1024, // chunk size: 64 KB
});
let chunks = 0;
stream.on("data", (chunk) => {
chunks++;
console.log("chunk " + chunks + ": " + chunk.length + " chars");
});
stream.on("end", () => console.log("done after " + chunks + " chunks"));
stream.on("error", (err) => console.error("read failed:", err.message));pipe and pipeline
Manually wiring data events to write calls is tedious and easy to get wrong. readable.pipe(writable) connects them, moving chunks automatically. Pipes chain through transforms: read file → gzip → write file is three streams and two pipes.
But .pipe() has a flaw: errors don't propagate across the chain, and a failure can leak resources. Modern code uses stream.pipeline(), which forwards errors to a single callback and cleans up every stream in the chain.
const fs = require("fs");
const zlib = require("zlib");
const { pipeline } = require("stream");
pipeline(
fs.createReadStream("access.log"), // Readable
zlib.createGzip(), // Transform
fs.createWriteStream("access.log.gz"), // Writable
(err) => {
if (err) console.error("pipeline failed:", err.message);
else console.log("file compressed");
}
);Backpressure: when the reader outruns the writer
A fast source (disk read) can overwhelm a slow destination (network upload). If chunks were queued without limit, memory would balloon. Backpressure is the flow-control mechanism that prevents this:
writable.write(chunk)returnsfalsewhen the internal buffer is over its limit (the highWaterMark)- A well-behaved producer then pauses reading
- When the writable drains, it emits
"drain"and the producer resumes
pipe and pipeline implement all this automatically — a huge reason to use them instead of manual data/write wiring.
// What pipe() does for you under the hood:
const fs = require("fs");
const source = fs.createReadStream("big-input.bin");
const dest = fs.createWriteStream("copy.bin");
source.on("data", (chunk) => {
const ok = dest.write(chunk);
if (!ok) {
source.pause(); // destination is full - stop reading
dest.once("drain", () => source.resume()); // resume when ready
}
});
source.on("end", () => dest.end());When to stream, when not to
Streams add ceremony, so use them where they pay off:
- Stream when data is large (video, logs, exports), unbounded (live feeds), or when you want to start responding before all data exists
- Don't stream small configuration files or short JSON bodies —
readFile/writeFileare simpler and just fine
Rule of thumb: if the whole payload comfortably fits in memory and arrives at once, skip streams. If it might not — stream it. HTTP responses, file uploads, and CSV exports are classic streaming wins.
Check your understanding
5 questionsQuestion 1 of 5
Score: 0
What does this code print?
const buf = Buffer.from("abc");
console.log(buf.length, buf.toString("hex"));