What is buffer in Node.js?
Buffer is a Node.js API to intract with octet streams in TCP streams, file systems operations, and other streams.
Buffer has many things to discuss in deep.But for the beginners or for normal use, we will discuss mainly on below three types to initialize a buffer in Node.js
Note: Earlier Buffer was initialised by calling buffer constructor using new keyword, but now its been deprecated, so we mailnly use either of the three below to initialize the buffer.
The size of the Buffer is assigned when it is created and cannot be changed further.
In our real world example:
Buffer is the waiting area where the data waits to be used/displayed.
If the rate of data coming from a stream is greater than the rate of data displaying or being used, those excess data waits in the buffer.
Buffer always interacts with the stream to get data and stores them as per defined size.
To get buffer class in application:
// To Create a zero-filled Buffer of length 10.
const buf1 = Buffer.alloc(10);
// To Create a Buffer of length 10, filled with 0x1.
const buf2 = Buffer.alloc(10, 1);
/* To Create an uninitialized buffer of length 10. This is faster than calling Buffer.alloc() but the returned Buffer instance might contain old data that needs to be overwritten using either fill() or write(). */
/*The value of an unsafe buffer is not emptied, and can contain data from older buffers*/
const buf3 = Buffer.allocUnsafe(5);
// To Create a Buffer containing [0x1, 0x2, 0x3].
const buf4 = Buffer.from([1, 2, 3]);
// To Create a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74].
const buf5 = Buffer.from('tést');
// To Create a Buffer containing Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf6 = Buffer.from('tést', 'latin1');
Character Encodings which Buffer accepts:
Difference between Buffer.alloc(), Buffer.allocUnsafe(), Buffer.from()
It creates a zero-filled Buffer of size length
It creates an uninitialized buffer of size length
This is faster than calling Buffer.alloc().
The returned Buffer instance might contain old data that needs to be overwritten using either fill() or write()
It returns a new Buffer that shares the same allocated memory as the given ArrayBuffer/Buffer