Buffer is a global object that provides a way to work with binary data directly.
A buffer is essentially an array of integers, where each integer represents a byte of data.
Buffers are particularly useful when dealing with streams, and I/O operations, such as reading from or writing to files, network operations, or handling binary data manipulation.
Concepts and Examples related to Node.js buffers:
We can create a buffer using the "Buffer.from()", "Buffer.alloc()", or "Buffer.allocUnsafe()" methods.
// Create a buffer from a string const bufferFromStr = Buffer.from('Hello, Node.js!'); // Create an uninitialized buffer of a specific size const uninitializedBuffer = Buffer.allocUnsafe(10); // Create a buffer with zeros of a specific size const zeroFilledBuffer = Buffer.alloc(5);
Buffers are essentially arrays of integers, where each element represents a byte.
const buffer = Buffer.from('Hello World, Node.js!'); // Access individual elements (bytes) of the buffer console.log(buffer[0]); // 72 console.log(buffer[1]); // 101
We can convert a "buffer" to a string using the "toString()" method.
const buffer = Buffer.from('Hello World, Node.js!'); const stringFromBuffer = buffer.toString(); console.log(stringFromBuffer); // 'Hello World, Node.js!'
Buffers can be written to or read from using various methods.
const buffer = Buffer.alloc(5); // Write data to the buffer buffer.write('Hello World'); // Read data from the buffer const data = buffer.toString(); console.log(data); // 'Hello World'
Buffers can be sliced to create new buffers that reference the same memory.
const buffer = Buffer.from('Hello World, Node.js!'); // Create a new buffer referencing a portion of the original buffer const slicedBuffer = buffer.slice(0, 12); console.log(slicedBuffer.toString()); // Hello World,
The length of a buffer can be determined using the "length" property.
const buffer = Buffer.from('Hello World, Node.js!'); console.log(buffer.length); // 21
Buffers can be copied using the "copy()" method.
const source = Buffer.from('Hello World, Nodejs'); const target = Buffer.alloc(19); // Copy data from source buffer to target buffer source.copy(target); console.log(target) // Hello World, Nodejs