🔍 What is a Buffer in Node.js?
A Buffer in Node.js is a special object used to store raw binary data. Unlike strings, which represent text characters, buffers store bytes. This makes them very useful for handling large files, network data, or any non-text data.
Example
const buf = Buffer.from('Hello, Node.js');
console.log(buf);
console.log(buf.toString());
Buffers store data in bytes, which can later be converted to readable text using toString().
🛠️ When to Use a Buffer
Buffers are helpful in situations where you need to handle binary data efficiently:
- Reading and writing files: especially large files.
- Handling network packets: when sending or receiving data over sockets.
- Working with streams: processing data in small chunks.
- Processing images, audio, or video data: when raw byte manipulation is needed.
💻 Example: Reading a File Using Buffer
Example
const fs = require('fs');
fs.readFile('example.txt', (err, data) => {
if (err) throw err;
console.log('Buffer content:', data); // Shows raw bytes
console.log('As string:', data.toString()); // Converts to text
});
Node.js reads the file as a buffer first, allowing you to process the raw bytes or convert them to a string.
💡 Buffer vs String
- Buffer: Stores raw bytes; suitable for any kind of data.
- String: Stores characters; best for readable text.
Example
const str = 'Hello';
const buf = Buffer.from(str);
console.log('String length:', str.length);
console.log('Buffer length:', buf.length);
Buffers are more flexible than strings when working with non-text data or large datasets.
📝 Summary
A Buffer in Node.js is used to store and manipulate raw binary data efficiently. It is especially useful for reading and writing files, handling network data, working with streams, and processing multimedia files. Unlike strings, buffers can handle any type of data, making Node.js applications faster and more memory-efficient.