Write to Buffers -
A string can be write to the buffer using the method
buffer.write(string, [offset], [length], [encoding])
, the method have four arguments, following are the arguments used in this method.
string - The string that has to be written in the buffer.
offset - The argument is an offset and is written through the particular offset buffer.
length -The argument defines size of data in bytes that are written to the buffer.
encoding – The argument is used write the first argument to the buffer.
The first argument is required argument and whereas the second, third and fourth are the optional argumnts.
The number of written octets are returned, when a buffer can’t fit the string due to insufficient space then a portion of the string is written. The example below is used to create a buffer using the
buffer.write()
method.
The method returns the value 26 which means, 26 bytes of the buffer have been written and even the given string “
SPLessons Online Tutorials” is 26.
Reading from buffer -
A string can be read from the buffer using the method buffer.toString([encoding], [strat], [end]), the function toString() is the member function of buffer object which is returned by the statement new Buffer();. The method have three arguments and all the three arguments are optional. Following are the three arguments.
encoding - A buffer is converted to a string of the given type of encoding using the buffer.toString() function.
Start - The argument set the position of the content of a buffer which has to be converted into a string.
End - The argument set the position of the content of a buffer which has to be converted into a string.
The example explains the working of read from buffer using the buffer.toString() method.