According to Nodejs.org we should use buffers because nodejs servers not only run on browsers but also uses TCP streams and reading and writing to the file system. For TCP streams and reading and writing to the file system it is mandatory to use pure binary streams of data.
Buffer is nothing but an array of integers which cannot be re-sized. It is a global object which means that you need not have to write require('buffer') for using it.
The encoding list used in Nodejs are :
1. var buffer = new Buffer(n); // where n is the size of the buffer
Ex : var buffer = new Buffer(10);
2. var buffer = new Buffer(arr); // where arr is a given array
Ex : var buffer = new Buffer([1, 2, 3, 4, 5, 6]);
3. var buffer = new Buffer(str, [encoding]);
// where str is any given string and encoding values are shown above
Ex : var buffer = new Buffer("hello world", 'utf8');
Writing To Buffers
buffer.write(string, [offset], [length], [encoding])
//where string is the given string, [offset] is from where you will start writing, [length] is the number of bytes to write, [encoding] is the encoding to use.
This function will return the number of octets written.
Reading From Buffers
buffer.toString([encoding], [start], [end])
//where [encoding] is the encoding to use, [start] states from where to start, [end] states where to end.
This function will return a string.
Please Like and Share the Blog, if you find it interesting and helpful.