4 min read
•Question 25 of 62mediumWhat is a Buffer in Node.js?
Understanding Buffers for handling binary data.
What You'll Learn
- What Buffers are
- Creating and using Buffers
- Common operations
What is a Buffer?
Buffer is a temporary storage for binary data. Used when dealing with TCP streams, file operations, or any binary data.
Creating Buffers
code.jsJavaScript
// Create buffer from string
const buf1 = Buffer.from('Hello');
// Create empty buffer of size 10
const buf2 = Buffer.alloc(10);
// Create buffer with unsafe allocation (faster, not zeroed)
const buf3 = Buffer.allocUnsafe(10);
// From array
const buf4 = Buffer.from([72, 101, 108, 108, 111]);Common Operations
code.jsJavaScript
const buf = Buffer.from('Hello World');
// Get length
console.log(buf.length); // 11
// Convert to string
console.log(buf.toString()); // 'Hello World'
console.log(buf.toString('hex')); // '48656c6c6f...'
console.log(buf.toString('base64')); // 'SGVsbG8gV29ybGQ='
// Slice buffer
const slice = buf.slice(0, 5);
console.log(slice.toString()); // 'Hello'
// Compare buffers
const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('ABC');
console.log(buf1.equals(buf2)); // true
// Concatenate buffers
const combined = Buffer.concat([buf1, buf2]);Use Case - Reading Binary File
code.jsJavaScript
const fs = require('fs');
fs.readFile('image.png', (err, buffer) => {
console.log(buffer); // <Buffer 89 50 4e 47...>
console.log(buffer.length); // file size in bytes
});