Working with Buffers

1. Creating Buffers

APIDescription
Buffer.from(str, "utf8")From string
Buffer.from(arr)From byte array
Buffer.from(buf)Copy
Buffer.from(arrayBuffer)Wrap ArrayBuffer (no copy)
Buffer.alloc(n)Zero-filled
Buffer.allocUnsafe(n)Uninitialized (faster)

2. Using Buffer.alloc vs Buffer.allocUnsafe

APISafetySpeed
allocZero-initializedSlower
allocUnsafeRandom memory contentsFaster — must overwrite before reading
allocUnsafeSlowBypasses poolFor long-lived buffers

3. Writing to Buffers

MethodUse
buf.write(str, offset, length, "utf8")Write string
buf.writeUInt8(v, off)1-byte unsigned
buf.writeInt32BE/LE32-bit signed (BE/LE)
buf.writeBigInt64BE64-bit signed
buf.fill(value)Fill bytes

4. Reading from Buffers

MethodReturns
buf.toString("utf8")Decoded string
buf.toString("hex") / "base64"Encoded string
buf.readUInt8(off)Byte value
buf.readInt32BE(off)32-bit big-endian
buf[i]Index byte access

5. Converting Encodings

EncodingUse
utf8Default text
utf16leUTF-16 little-endian
latin11 byte/char (binary string)
ascii7-bit only
base64 / base64urlBinary-safe text
hexTwo chars per byte

Example: Convert

Buffer.from("aGVsbG8=", "base64").toString("utf8"); // "hello"

6. Checking Buffer Length

APIReturns
buf.lengthBytes
Buffer.byteLength(str, "utf8")Bytes a string would take

7. Comparing Buffers

APIReturns
buf.equals(other)Boolean
Buffer.compare(a, b)-1/0/1 (sortable)

8. Concatenating Buffers (Buffer.concat)

Example

const merged = Buffer.concat([a, b, c], a.length + b.length + c.length);

9. Copying Buffers

APIBehavior
buf.copy(target, targetStart, srcStart, srcEnd)Bytes copied
Buffer.from(buf)Full deep copy

10. Slicing Buffers

APINotes
buf.subarray(start, end)Shares memory (preferred)
buf.slice(...)DEPRECATED — use subarray

11. Understanding Buffer Pooling

ConceptDetail
Buffer.poolSizeDefault 8 KB shared pool
Buffer.allocUnsafeUses pool when size < poolSize/2
Long-lived buffersUse allocUnsafeSlow to avoid keeping pool alive