What are Buffers and when do you need them over strings?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Buffer is Node's fixed-size raw binary data type — sequences of bytes outside V8's heap. Use it for binary protocols, file/network chunks, hashing, encodings. Strings are UTF-16 internally and imply character encoding semantics buffers don't have.
Detailed explanation
JavaScript strings encode characters; network and disk speak bytes. Buffer bridges them: allocates fixed byte arrays outside the regular object heap, exposing binary-safe reads/writes with explicit encoding control (utf8, base64, hex, latin1...). You meet them constantly without noticing — stream chunks ARE buffers, crypto.digest returns one, fs.readFileSync without encoding returns one. Converting carelessly costs correctness and performance: buf.toString('utf8') on multi-byte characters split across chunk boundaries corrupts text (streaming decoders like StringDecoder fix this); string concatenation re-encodes repeatedly where buffer.concat copies once efficiently. TypedArrays overlap conceptually (Buffer subclasses Uint8Array) but Buffer adds encoding-aware APIs and pooling. Practical rules: stay in buffers through transformations, convert to string once at boundaries, specify encoding explicitly everywhere rather than trusting defaults.
Example
import crypto from 'node:crypto';
const payload = Buffer.from('hello world', 'utf8');
const hash = crypto.createHash('sha256').update(payload).digest('hex');
// Binary-safe round trip:
const encoded = payload.toString('base64'); // send as text
const decoded = Buffer.from(encoded, 'base64');
decoded.toString('utf8'); // 'hello world'
payload.byteLength; // 11 — actual bytes, unlike string lengthInterview tip
Open with 'strings are characters, networks speak bytes' then give the split-multibyte-chunk bug — it proves hands-on stream experience instantly.
Common mistakes
- Calling toString() per-chunk in streams with multibyte content.
- Not knowing Buffer extends Uint8Array.