Buffer (Node.js)
A Buffer is a Node.js object for handling raw binary data — bytes — outside the V8 heap. It is used for file contents, network packets, and any binary I/O, and can convert to and from strings using an encoding.
Node.js
JavaScript strings are text, but file and network data is raw bytes. Buffer is Node's fixed-length sequence of bytes for that binary data. Stream chunks, fs reads without an encoding, and TCP packets all come to you as Buffers.
You create them with Buffer.from('text', 'utf8') (from a string or array) or Buffer.alloc(size) (a zero-filled buffer of n bytes). Converting back to text uses buf.toString('utf8'), and you can specify encodings like 'hex' or 'base64' for binary-to-text conversion.
Buffers live outside V8's garbage-collected heap, so they handle large binary data efficiently, but their size is fixed at creation. Use the safe Buffer.alloc rather than the deprecated, unsafe new Buffer(size), which could expose old memory contents.
Syntax
Buffer.from("text", "utf8") Buffer.alloc(n)Examples
JavaScript
const buf = Buffer.from("Hi", "utf8");
console.log(buf); // <Buffer 48 69>
console.log(buf.toString("hex")); // 4869
console.log(buf.length); // 2Output:
<Buffer 48 69>
4869
2