Buffer basics
A Buffer is a fixed-size chunk of raw bytes, used for binary data like files and network packets.
In this page:
Syntax
const buf = Buffer.from('text', 'utf8');
const empty = Buffer.alloc(size);
buf.toString('hex');
Buffer basics
Buffer.from creates a buffer from a string, array or another buffer, and Buffer.alloc creates a zero-filled one. toString converts bytes back to text using an encoding such as utf8, hex or base64. Buffers are a subclass of Uint8Array.
Note:
Buffer.alloc is safer than the old Buffer constructor because it zero-fills memory.
Example: Buffer basics
const b = Buffer.from("héllo", "utf8");
console.log("chars:", "héllo".length, "bytes:", b.length);
console.log(b.toString("hex"));
console.log(Buffer.from("Node").toString("base64"));
console.log(Buffer.alloc(3));
// Output:
// chars: 5 bytes: 6
// 68c3a96c6c6f
// Tm9kZQ==
// <Buffer 00 00 00>
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using the deprecated new Buffer()
- Mixing up string length and byte length
- Forgetting the encoding when converting
Chapter Summary
- Buffer holds raw bytes
- from and alloc create buffers
- toString takes an encoding
- Buffers are Uint8Arrays
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: