What is a Buffer in Node.js?
1. Definition
A Buffer in Node.js is a temporary memory area used to store binary data. It is mainly used when working with streams or handling raw data like files, network requests, or images.
2. Why We Use Buffer
- To handle binary data directly
- Used in file system operations
- Helps in streaming data efficiently
- Works with network data (TCP, HTTP)
3. How Buffer Works
- Stores data in raw binary format
- Fixed-size memory allocation
- Data is processed in chunks
4. Example
// Create buffer
const buffer = Buffer.from("Hello");
// Convert to string
console.log(buffer.toString());
// Access raw data
console.log(buffer);5. Output
Hello <Buffer 48 65 6c 6c 6f>
6. Advantages
- Efficient handling of binary data
- Fast data processing
- Essential for streams and file handling
- Low-level memory control