Node.js
/Intermediate
Buffers
Definition
A core Node.js class used to represent fixed-length sequences of bytes. It is Node's way of interacting with raw binary data.
Explain Like I'm New
JavaScript was designed for strings and numbers. It was never meant to read raw image data or video pixels (which are just 0s and 1s). A Buffer is a temporary storage area in memory explicitly designed to hold raw binary data coming from Streams or the File System before it is processed.
Real World Example
If you use `fs.readFile('image.png')`, Node doesn't return a string. It returns a `<Buffer 89 50 4e 47 ... >`. These are the raw hexadecimal bytes of the image.
Common Use Cases
- •File uploads
- •Image/Video processing
- •Cryptography
Terminal Output
bash / terminal
// 1. Creating a Buffer from a String
const myBuffer = Buffer.from("Hello World", "utf-8");
console.log("Raw Buffer (Hex):", myBuffer);
// Output: <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>
// 2. Converting back to a String
console.log("Decoded String:", myBuffer.toString());
// 3. Allocating a fixed-size empty Buffer (10 bytes)
const emptyBuf = Buffer.alloc(10);
emptyBuf.write("Node"); // Writes to the first 4 bytes
console.log("Allocated Buffer:", emptyBuf);
// 4. Checking length (in Bytes, NOT characters)
const emojiBuf = Buffer.from("🔥");
console.log("String length:", "🔥".length); // 2 (JS quirk)
console.log("Buffer byte length:", emojiBuf.length); // 4 (Emojis take 4 real bytes!)
Interview Questions
basic
- What does a Buffer hold?
intermediate
- What happens if you print a Buffer to the console without calling `.toString()` on it?
advanced
- Can you resize a Buffer after it is created?