buffer
The Buffer
class provides a way to work with raw binary data directly. Buffers are used when dealing with files, sockets, or binary protocols.
API Surface
Creation
Buffer.alloc(size)
— allocate a zero‑filled buffer.Buffer.allocUnsafe(size)
— allocate without fill (faster, but old data may remain).Buffer.from(array)
— from byte array.Buffer.from(string, [encoding])
— from string with encoding (utf8
,base64
,hex
, etc.).
Conversion
buf.toString([encoding])
— decode to string.buf.toJSON()
— JSON representation.
Indexing
buf[i]
— get/set byte at index.
Copy & Slice
Buffer.concat(list[, totalLength])
— join multiple buffers.buf.slice(start, end)
— view into part of the buffer.
Read & Write
buf.write(string, [offset], [length], [encoding])
buf.readInt8(offset)
,buf.readUInt16LE(offset)
, etc.buf.writeInt32BE(value, offset)
, etc.
Properties
buf.length
— size in bytes.Buffer.isBuffer(obj)
— check type.Buffer.byteLength(string, [encoding])
— size in bytes when encoded.
Examples (English only)
// Create buffers
const b1 = Buffer.alloc(5);
const b2 = Buffer.from("Hello");
const b3 = Buffer.from("SGVsbG8=", "base64");
console.log(b1, b2.toString(), b3.toString());
// Index access
b2[0] = 0x68; // overwrite 'H' with 'h'
console.log(b2.toString());
// Slice & concat
const part = b2.slice(0, 2);
console.log(part.toString());
const joined = Buffer.concat([b2, Buffer.from(" world")]);
console.log(joined.toString());
// Read & write numbers
const buf = Buffer.alloc(4);
buf.writeInt32BE(12345, 0);
console.log(buf.readInt32BE(0));
Notes
- Prefer
Buffer.alloc
overallocUnsafe
for security and correctness. - Buffers are fixed-size; slicing does not copy but creates a view.
- Always specify encoding (
utf8
,base64
,hex
) when converting strings. - Use typed read/write methods for structured binary protocols.