Buffer
Why Buffer exists
Section titled “Why Buffer exists”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.
Creating a Buffer
Section titled “Creating a Buffer”The preferred way is Buffer.from(). The deprecated new Buffer() constructor was removed; never use it.
Needs the Node.js runtime — open in StackBlitz to run.
Encodings: utf8, hex, base64
Section titled “Encodings: utf8, hex, base64”toString(encoding) converts a Buffer back to a string in the requested encoding.
Needs the Node.js runtime — open in StackBlitz to run.
Byte length vs string length
Section titled “Byte length vs string length”Needs the Node.js runtime — open in StackBlitz to run.
Slicing and copying
Section titled “Slicing and copying”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.
Needs the Node.js runtime — open in StackBlitz to run.