Node.js ยท Chapter 10 of 43

Buffers

A Buffer is a temporary storage area for raw binary data, used when Node.js works with streams, files, or network protocols that deal in bytes rather than text.

Buffers exist because JavaScript originally had no way to handle raw binary data directly.

Creating buffers

You can create buffers from strings, arrays, or pre-allocated sizes using `Buffer.from()` or `Buffer.alloc()`.

Buffers and encoding

Buffers store raw bytes; converting between buffers and strings requires specifying an encoding like 'utf8' or 'hex'.

Example 1 (javascript)
const buf = Buffer.from('Hello');
console.log(buf);
console.log(buf.toString());
Output
<Buffer 48 65 6c 6c 6f>
Hello

The buffer stores the bytes of 'Hello'; toString() converts back to text.

Example 2 (javascript)
const buf = Buffer.alloc(4);
buf.write('AB');
console.log(buf);
Output
<Buffer 41 42 00 00>

alloc() reserves 4 bytes of memory, initially filled with zeros.

Key points

  • Buffers hold raw binary data.
  • Buffer.from() creates a buffer from existing data.
  • Buffer.alloc() pre-allocates a fixed-size buffer.
  • toString() converts buffer bytes back into readable text.
๐Ÿ’ก Note: You'll see Buffers most often when working with files, streams, and TCP sockets.

๐Ÿ“ Quick Quiz

1. What does a Buffer store?

2. Which method converts a buffer's bytes into text?

3. Which method pre-allocates a buffer of a fixed size?