Loading lessons...
Working with Binary Data: Buffers
What is a Buffer?
A Buffer is a global Node.js class used to store raw binary data in fixed-length, off-heap memory allocations outside V8's heap.
Creating Buffers
// 1. Create buffer from a string
const bufFromString = Buffer.from("Node.js", "utf-8");
console.log(bufFromString); // <Buffer 4e 6f 64 65 2e 6a 73>
console.log("Byte length:", bufFromString.length); // 7 bytes
// 2. Allocate fixed size zero-filled buffer
const bufAlloc = Buffer.alloc(10); // 10 bytes initialized with 0
bufAlloc.write("Express");
console.log(bufAlloc.toString()); // 'Express '
// 3. Convert Buffer back to String or JSON
console.log("Decoded String:", bufFromString.toString("utf-8"));
console.log("JSON representation:", bufFromString.toJSON());
Why Buffers Matter
- Image and audio/video file processing.
- Receiving network TCP socket packets.
- Encrypting and decrypting payloads with cryptographic modules.
TL;DR
- Buffers hold fixed-length sequences of raw binary bytes outside V8 heap.
- Use
Buffer.from()to encode strings andBuffer.alloc()for pre-sized memory blocks.