Handbooks / Node.js / Chapter 4
Streams and Buffers
7 pages · ~5 min✓ Reviewed
Builds on Core Modules: fs, path, http and os. Next up: Express Routing and Middleware.
Buffers: Raw Bytes in Node
1. What a Buffer is
- Fixed-size chunk of raw bytes; cannot be resized
- A
Uint8Arraysubclass - Allocated outside the V8 heap
2. Create and convert
| Call | Result |
|---|---|
Buffer.from('hi', 'utf8') | bytes of the string |
Buffer.alloc(n) | zero-filled |
Buffer.allocUnsafe(n) | faster, may hold old memory |
buf.toString('utf8'|'hex'|'base64') | bytes to string |
Buffer.concat([a, b]) | new buffer, copies |
buf.subarray() / slice() | shares memory, no copy |
3. Gotchas
allocUnsafe: overwrite before use, or old data leaks- Writing to a slice changes the original
chunk.toString()per chunk splits multi-byte characters
javascript
r.setEncoding('utf8') // or a decoder: const d = new StringDecoder('utf8') text += d.write(chunk)
decoders hold back partial characters
The Four Stream Types
1. What a Stream Is
- Data moves in chunks, so memory stays flat at any size
- Streams are EventEmitters
- Chunk is a
Buffer, or a string aftersetEncoding()
2. The Four Types
| Type |
|---|
pipe, pipeline and Backpressure
1. Backpressure
- Slow consumer tells fast producer to stop
write()returnsfalse→ wait for'drain'- Threshold is highWaterMark (buffer size)
| Stream | highWaterMark default |
|---|
Reading Files Efficiently
1. readFile Loads It All
fs.readFile/fs.promises.readFileload the whole file into memory- Fine for small files
- Large files: memory spikes, may hit the Buffer size limit
2. Chunks and Lines
- Default chunk of a file read stream: 64 KiB
Common Stream Mistakes
1. pipe() and errors
pipe()forwards no errors and destroys nothing- One stage fails, the others stay open: file descriptor leak
- Fix:
pipeline()destroys every stage and rejects once
javascript
const { pipeline } = require('node:stream/promises'); try { await pipeline(src, gzip, dest); } catch (err) { console.error(err); }
2. Ignored write()
Buffers and Streams Cheat Sheet
1. Buffers
| Call | Does |
|---|---|
Buffer.from(x, enc) | build from string or array |
Buffer.alloc(n) | zero-filled |
Buffer.allocUnsafe(n) | fast, may hold old memory, overwrite it |
Check yourself
A loop calls w.write(line) a million times on a file stream and ignores the result. What goes wrong?
- Memory balloons:
write()returns false when full, but data keeps queueing. - Fix: when false, await
events.once(w, 'drain').
What does this print?
Hello: subarray shares memory, no copy.- 72 is the code for 'H'.
const b = Buffer.from('hello'); const s = b.subarray(0, 2); s[0] = 72; console.log(b.toString());