Skip to the page

Events, buffers, streams and files · mid

Buffers, bytes and encodings

A Buffer is a fixed-size chunk of raw bytes (a Uint8Array subclass) that Node uses for files, sockets and crypto, and you must think in bytes and encodings, because one character can take 1 to 4 bytes in UTF-8.

The notes

What you must know

  • Create: Buffer.from(string, encoding), Buffer.from(array), Buffer.alloc(size) (zero-filled, safe), Buffer.allocUnsafe(size) (faster, contains old memory: overwrite it fully).
  • Encodings: utf8 (default), base64, base64url (URL-safe; used in JWTs), hex, latin1. buf.toString(encoding) converts back.
  • string.length counts UTF-16 code units; Buffer.byteLength(str) counts bytes. Content-Length, body limits and DB column limits are in bytes.
  • buf.subarray() (and the deprecated buf.slice()) shares memory with the original; Buffer.from(buf) copies.
  • Collect stream chunks in an array and Buffer.concat them at the end. Decoding each chunk on its own can split a multi-byte character; use setEncoding('utf8'), StringDecoder or TextDecoder with { stream: true }.
  • Compare secrets with crypto.timingSafeEqual(a, b) (same length required), not === or buf.equals, to avoid timing attacks.

The red pen

Common traps: mistake → fix

  • Mistake: String length equals byte size

    Fix: 'héllo' has length 5 but is 6 bytes in UTF-8; '€' is 3 bytes.

  • Mistake: subarray copies the data

    Fix: it is a view on the same memory; writing to it changes the original.

  • Mistake: base64 hides data

    Fix: it is an encoding anyone can reverse; JWT payloads are only base64url, not encrypted.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a Buffer and why does Node need it?
  2. String length vs byte length: where does it matter in an API?
  3. How do you safely build a string from many stream chunks?
  4. base64 vs base64url: where have you used base64url?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview