CodeBlanks Logo Icon CodeBlanks

What is Buffer?

Learn binary data management with Buffer.

What is Buffer?

A Buffer in Node.js is an object that holds fixed-size binary data. It allocates raw memory outside the V8 heap. You use it whenever you work with byte sequences: file reading, network streams and cryptography.

Regular JavaScript arrays can hold numbers, but each element carries overhead. A Buffer works directly at the byte level: every element is a value from 0 to 255. You create one with Buffer.alloc(4), which fills four bytes with zeros. The output shows <Buffer 00 00 00 00>.

The structure of a Buffer

A buffer's length is fixed when it is created and cannot change. The buf.length property gives the byte count. You can access each byte with buf[i], which returns a number from 0 to 255.

For example Buffer.from("Ab") makes a two-byte buffer: buf[0] is 65 (the ASCII code of A) and buf[1] is 98. Buffers are mutable: writing buf[0] = 66 turns the first byte into the letter B. Unlike strings, a buffer's contents can be changed in place.

Practice Create a buffer and print it

Create a four-byte buffer with Buffer.alloc(4). Print it with console.log.

Starter code

index.js
// Create a four-byte buffer
// write here

// Print the buffer
// write here

Sample solution

index.js
const buf = Buffer.alloc(4);
console.log(buf);

Expected output

<Buffer 00 00 00 00>

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is Buffer used for?

index.js
Buffer.alloc(4)
  • To work with binary data Correct answer
  • Only to store text
  • To define classes
  • To manipulate the DOM

Explanation: Buffer holds binary data at the byte level.

2 Create a buffer

Question
const buf = Buffer.____(4);
Answer
const buf = Buffer.alloc(4);

Explanation: Buffer.alloc(4) creates a four-byte zero-filled buffer.

3 Match each piece to its role

Term Meaning
Buffer Holds binary data
buf.length Gives byte count
buf[0] Accesses first byte
0-255 Value range of a byte

All lessons in Intermediate