buffer — Buffer
Working with binary data in Node.js — Buffer.from, Buffer.alloc, encodings, converting to/from strings, and the relationship with Uint8Array.
Small Buffers don't get their own memory. Node carves them out of a shared, pre-allocated 8 KB pool. buf.buffer is that whole shared ArrayBuffer, so new Uint8Array(buf.buffer) isn't "the same bytes": it's 8,192 bytes of other Buffers' data, starting at the wrong place. Hand buf.buffer to a browser API, a worker or a typed-array parser and it silently reads the wrong data.
const buf = Buffer.from("Hi"); // small buffers share one pre-allocated pool
const view = new Uint8Array(buf.buffer); // meant: "the same two bytes"
console.log(buf.length, view.length);
console.log("starts at byte", buf.byteOffset, "of a shared", buf.buffer.byteLength, "byte block");
// 2 8192
// starts at byte 320 of a shared 8192 byte block (the offset varies)Binary data in Node.js
In the browser, binary data is Uint8Array. In Node.js, that's Buffer
— a subclass of Uint8Array with extra convenience methods. You encounter Buffers
when reading files, receiving HTTP bodies, working with crypto, or using any binary protocol.
Creating Buffers
// From a string:
const buf = Buffer.from("Hello", "utf-8");
console.log(buf); // <Buffer 48 65 6c 6c 6f>
console.log(buf.length); // 5 (bytes, not characters)
// From a hex string:
const hex = Buffer.from("cafebabe", "hex");
console.log(hex); // <Buffer ca fe ba be>
// From base64:
const b64 = Buffer.from("SGVsbG8=", "base64");
console.log(b64.toString("utf-8")); // "Hello"
// Zeroed (safe — all bytes set to 0):
const empty = Buffer.alloc(16);
// Uninitialised (faster but UNSAFE — may contain old memory):
const unsafe = Buffer.allocUnsafe(16); // always fill before use!Converting Buffers
const buf = Buffer.from("The Codex", "utf-8");
// To string in any encoding:
buf.toString("utf-8"); // "The Codex"
buf.toString("base64"); // "VGhlIENvZGV4"
buf.toString("hex"); // "54686520436f646578"
buf.toString("latin1"); // same as utf-8 for ASCII
// To ArrayBuffer (for browser APIs):
const arrayBuf = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
// Concatenate buffers:
const a = Buffer.from("Hello ");
const b = Buffer.from("World!");
const c = Buffer.concat([a, b]);
console.log(c.toString()); // "Hello World!"That's why the "To ArrayBuffer" line above slices with buf.byteOffset and buf.byteLength. Whenever you reach for buf.buffer, take the offset and length with it:
const buf = Buffer.from("Hi");
const view = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); // only this Buffer's bytes
console.log(buf.length, view.length);
console.log(Buffer.from(view).toString());
// 2 2
// HiOfficial Sources
The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.