Buffers

Node's Raw Bytes — Before Strings Existed

Buffers

Buffer is Node's binary-data type. Bytes in, bytes out — for files, network, crypto.

3 min read Level 2/5 #nodejs#buffer#binary
What you'll learn
  • Create and inspect a Buffer
  • Convert between Buffer and string
  • Know when you need them

A Buffer is a fixed-size chunk of binary data. Node predates Uint8Array and ArrayBufferBuffer is its byte type, and it extends Uint8Array.

Creating

Buffer.from("hello");                    // from a string
Buffer.from("48656c6c6f", "hex");         // from hex
Buffer.from([72, 101, 108, 108, 111]);    // from a byte array
Buffer.alloc(16);                          // 16 zero bytes
Buffer.allocUnsafe(16);                    // 16 unspecified bytes (faster)

Inspecting

const b = Buffer.from("hello");
console.log(b);              // <Buffer 68 65 6c 6c 6f>
console.log(b.length);       // 5
console.log(b[0]);           // 104 ('h')
console.log(b.toString());   // "hello"
console.log(b.toString("hex"));   // "68656c6c6f"
console.log(b.toString("base64")); // "aGVsbG8="

Why You’ll Meet Them

  • readFile(path) (no encoding) returns a Buffer
  • crypto.randomBytes() returns a Buffer
  • Reading from a socket returns Buffers
  • Image/binary data — Buffers all the way

Converting

// Buffer → string
buf.toString("utf8");
buf.toString("base64");

// string → Buffer
Buffer.from("text", "utf8");

// Buffer ↔ ArrayBuffer (Web API standard)
const u8 = new Uint8Array(buf);
const back = Buffer.from(u8);

Buffer vs Uint8Array

A Buffer is a Uint8Array (it inherits from it). The difference: Buffer has extra Node-specific methods (toString("hex"), slice that shares memory, write methods).

Modern code prefers Uint8Array for portability — same bytes, works in browsers and Deno too.

The crypto Module →