Node.js — Buffers
What are Buffers?
Buffers handle binary data directly.
Creating Buffers
// From string
const buf1 = Buffer.from('Hello');
// From array
const buf2 = Buffer.from([72, 101, 108, 108, 111]);
// Allocate
const buf3 = Buffer.alloc(10);
Buffer Methods
const buf = Buffer.from('Hello World');
buf.toString() // 'Hello World'
buf.length // 11
buf[0] // 72 (H)
buf.toString('base64') // Base64 encoded
buf.toString('hex') // Hex encoded
Manipulating Buffers
const buf = Buffer.alloc(5);
buf.write('Hello');
const buf2 = Buffer.concat([buf, Buffer.from(' World')]);
console.log(buf2.toString()); // 'Hello World'
Encoding Types
| Encoding | Description |
|---|---|
| utf8 | Default, UTF-8 |
| ascii | ASCII |
| base64 | Base64 |
| hex | Hexadecimal |
| binary | Binary |
Practical Example
// Convert string to Base64
const encoded = Buffer.from('Hello').toString('base64');
// Convert Base64 back
const decoded = Buffer.from(encoded, 'base64').toString();
Mini Practice
- Create buffers from strings
- Convert between encodings
- Concatenate buffers
- Read and write binary data
Up Next
Continue with Timers — scheduling code execution.
Related Topics
Frequently Asked Questions about Buffers
What is Buffers in Node.js?
Buffers is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Buffers?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Buffers.
Why is Buffers important in Node.js?
Buffers is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.