Skip to content

Buffer

JavaScript strings are stored internally as UTF-16 — two bytes per code point in the Basic Multilingual Plane. That is fine for text, but networking and filesystem work deals in raw bytes: a TCP packet, a JPEG image, or a binary protocol frame has no inherent encoding.

Buffer is Node’s answer: a fixed-length sequence of bytes exposed as a Uint8Array subclass. It predates typed arrays and is still the standard type you will see throughout Node’s streams, HTTP, crypto, and fs APIs.

The preferred way is Buffer.from(). The deprecated new Buffer() constructor was removed; never use it.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

toString(encoding) converts a Buffer back to a string in the requested encoding.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

buf.slice(start, end) (or buf.subarray) returns a view into the same memory — modifying the slice modifies the original. Use Buffer.from(slice) to get an independent copy.

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Why is Buffer.byteLength(str) often different from str.length?
What does Buffer.from("deadbeef", "hex") produce?
What happens when you mutate a slice returned by buf.slice()?