The Codex / JavaScript / buffer — Buffer

buffer — Buffer

Working with binary data in Node.js — Buffer.from, Buffer.alloc, encodings, converting to/from strings, and the relationship with Uint8Array.

What it is, in plain English: A Buffer in Node.js is a fixed-length sequence of raw bytes — Node's equivalent of the browser's Uint8Array (and in fact a subclass of it). Buffers are used everywhere binary data appears: reading files, HTTP bodies, cryptographic operations, network protocols. Buffer.from() creates a buffer from a string, array, or ArrayBuffer. Buffer.alloc() creates a zeroed buffer of a given size.

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!"
Try It Yourself

Official Sources

The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.