Buffers

Buffers hold raw binary data outside the normal JavaScript heap.

SyntaxBuffer.from('text', 'utf8')

A Buffer is a fixed-length chunk of raw binary data. Because JavaScript strings cannot represent arbitrary bytes, Node uses Buffers for files, network packets, and other binary data.

Where you meet them

When you read a file without an encoding, you get a Buffer. Call .toString('utf8') to turn it into text.

Example

Example · javascript
const buf = Buffer.from('Hi');
console.log(buf);              // <Buffer 48 69>
console.log(buf.length);       // 2
console.log(buf[0]);           // 72 (code for 'H')
console.log(buf.toString());   // Hi

When to use it

  • A network protocol parser reads raw TCP packets into a Buffer to extract fixed-length binary headers before converting them to structured objects.
  • An image thumbnail service reads JPEG binary data into a Buffer, passes it to Sharp for resizing, and writes the output Buffer to disk.
  • A cryptography module creates a random 32-byte Buffer with `crypto.randomBytes` to generate a secure session token.

More examples

Create and inspect a Buffer

Creates a Buffer from a string, shows its raw byte representation, and converts it back to a string.

Example · js
const buf = Buffer.from('Hello, Node!', 'utf8');
console.log(buf);           // <Buffer 48 65 6c 6c 6f ...>
console.log(buf.length);    // 12
console.log(buf.toString()); // 'Hello, Node!'

Allocate and fill a Buffer

Uses `Buffer.alloc` for safe (zero-filled) allocation and demonstrates writing/reading a 32-bit integer.

Example · js
// Safe allocation -- zero-fills the memory
const safe = Buffer.alloc(8);
console.log(safe); // <Buffer 00 00 00 00 00 00 00 00>

safe.writeUInt32BE(42, 0); // write 42 at byte offset 0
console.log(safe.readUInt32BE(0)); // 42

Convert between encodings

Converts a Buffer to base64 and hex encodings then decodes it back -- common for binary data transport.

Example · js
const raw  = Buffer.from('Node.js Buffers', 'utf8');
const b64  = raw.toString('base64');
const hex  = raw.toString('hex');

console.log('base64:', b64);
console.log('hex:   ', hex);
// Decode back
console.log(Buffer.from(b64, 'base64').toString('utf8'));

Discussion

  • Be the first to comment on this lesson.