devnotes.

Working with Buffers

JavaScript strings are great for text, but not everything Node.js touches is text — image bytes, network packets, encrypted data, and raw file contents are all binary. Buffer exists to represent exactly that: a fixed-length chunk of raw memory, holding pure binary data outside JavaScript's usual string-encoding rules.

Creating a Buffer

const fromString = Buffer.from('Hello Node.js');
const fromArray = Buffer.from([72, 101, 121]); // raw byte values
const empty = Buffer.alloc(10); // 10 bytes, all zeroed out

console.log(fromString);        // <Buffer 48 65 6c 6c 6f 20 4e 6f 64 65 2e 6a 73>
console.log(fromString.length); // 13 — byte length, not character count

That <Buffer 48 65 6c ...> output is the raw data shown in hexadecimal — each pair of hex digits is one byte.

Converting back to a readable string

console.log(fromString.toString('utf8')); // 'Hello Node.js'
console.log(fromString.toString('hex'));  // '48656c6c6f204e6f64652e6a73'
console.log(fromString.toString('base64')); // 'SGVsbG8gTm9kZS5qcw=='

A Buffer is not an array, even though it looks like one

const buf = Buffer.alloc(5);
console.log(Array.isArray(buf));   // false
console.log(Buffer.isBuffer(buf)); // true

A regular JavaScript array can hold any mix of types and grow or shrink freely. A Buffer is fixed in size the moment it's created and holds only raw bytes — closer to a low-level memory block than a flexible list.

Common buffer operations

const greeting = Buffer.from('Hi ');
const name = Buffer.from('Rahim');
const combined = Buffer.concat([greeting, name]);
console.log(combined.toString()); // 'Hi Rahim'

const source = Buffer.from('ABCDE');
const slice = source.subarray(0, 3);
console.log(slice.toString()); // 'ABC'

Where you'll actually run into Buffers

Most application code never manually creates one — Buffers show up naturally when reading binary files (fs.readFile without an encoding option returns one), receiving raw HTTP request bodies before you've parsed them, or working with streams, TCP sockets, and cryptographic functions. Understanding what a Buffer is prevents a common early confusion: calling .toString() on binary data you receive from one of these APIs, and getting garbled output because you assumed it was already text.

Working with Buffers | DevNotes