Skip to content
Node.js

Buffers

Work with binary data using Buffer and TypedArrays.

#buffer#binary#encoding

Code

nodejs
// Allocate buffers
const buf = Buffer.alloc(8);            // zero-filled
const unsafe = Buffer.allocUnsafe(8);   // uninitialized, faster
const fromStr = Buffer.from("hello", "utf8");
const fromHex = Buffer.from("48656c6c6f", "hex");

// Read and write
buf.writeUInt32BE(0x12345678, 0);
const n = buf.readUInt32BE(0);
console.log(n.toString(16));            // 12345678

// Convert between encodings
const b64 = fromStr.toString("base64");
const decoded = Buffer.from(b64, "base64").toString("utf8");

// Concat and slice
const combined = Buffer.concat([fromStr, Buffer.from("!")]);
const slice = combined.subarray(0, 3);

// Iterate bytes
for (const byte of combined) {
  // byte is 0-255
}