The Buffer.toString() method is used to decode a buffer data to string according to the specified encoding type. The start and end offset is used to decode only particular subset of a buffer. If the byte sequence in the buffer data is not valid according to the provided encoding, then it is replaced by the default replacement character i.e. U+FFFD.
Buffer.toString( encoding, start, end )
Parameters: This method accept two parameters as mentioned above and described below:
- encoding: The format in which the buffer data characters has to be encoded. Its default value is ‘utf8’.
- start: The beginning index of the buffer data from which encoding has to be start. Its default value is 0.
- end: The last index of the buffer data up to which encoding has to be done. Its default value is Buffer.length.
Return Value: It returns decoded string from buffer to string according to specified character encoding.
abcde bcd 6162636465
Explanation: In the above example, we have declared a variable buffer with size of 5 and have filled with ASCII value from ‘a’ to ‘e’. Next, we have used toString() method without any parameters, that returns the string with default encoding style i.e. ‘UTF-8’ of complete buffer. On the next line, it returns the string with encoding style of ‘UTF-8’ from index 1 to 3 (here, 4 is excluded). At last, it returns the string representation with encoding style of ‘HEX’.
Note: The above program will compile and run by using the
node index.js command.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.