Node.js Buffers
In Node.js, the Buffer class handles raw binary data. Buffers represent fixed-size memory allocations outside the V8 heap, essential for file system operations, TCP streams, and any low-level byte manipulation.
Node.js Tutorial:-
Complete Python Course:-
Buffer is a global class ÔÇö no import required.
Creating Buffers (Modern API)
The older new Buffer() is DEPRECATED. Use these safer modern methods:
// Allocate an empty 10-byte buffer (zero-filled)
const buf1 = Buffer.alloc(10);
// From an array of bytes
const buf2 = Buffer.from([10, 20, 30, 40, 50]);
// From a string
const buf3 = Buffer.from('Simply Easy Learning', 'utf-8');
Writing to Buffers
const buf = Buffer.alloc(256);
const len = buf.write("Simply Easy Learning");
console.log("Octets written:", len);
// Output: Octets written: 20
Reading from Buffers
const buf = Buffer.alloc(26);
for (let i = 0; i < 26; i++) {
buf[i] = i + 97;
}
console.log(buf.toString('ascii')); // abcdefghijklmnopqrstuvwxyz
console.log(buf.toString('ascii', 0, 5)); // abcde
console.log(buf.toString('utf8', 0, 5)); // abcde
Useful Buffer Methods
Buffer.alloc(size)ÔÇö zero-filled buffer.Buffer.allocUnsafe(size)ÔÇö faster, but uninitialized (may contain old data).Buffer.from(string | array)ÔÇö buffer from data.buf.lengthÔÇö buffer size in bytes.buf.toString(encoding)ÔÇö decode to string.Buffer.concat([buf1, buf2])ÔÇö join buffers.
Download New Real Time Projects:- Click here
Complete Advance AI topics:-
Conclusion
Buffers are Node.js’s way of handling raw binary data efficiently. Always use Buffer.alloc and Buffer.from in modern code, never the deprecated new Buffer(). For more tutorials, stay tuned to .
node js buffer example
node js buffers w3schools
streams and buffers in node js
how to create buffer in node js
buffer – npm
nodejs buffer to string
nodejs buffer to base64
buffer from base64