What is the Node.js Buffer.toString() method?
In Node.js, the Buffer.toString() method is used to decode or convert a buffer to a string, according to the specified character encoding type. Converting a buffer to a string is known as encoding, and converting a string to a buffer is known as decoding.
Syntax
Buffer.toString( encoding, start, end )
Parameters
encoding: This is the format in which the buffer data has to be encoded. The encodings supported by Node.js includeutf8,utf16le, andlatin1.
uft8is the default ifencodingis not specified.
start: This references the beginning data of the buffer. It starts from 0, meaning that the first data starts from 0.
The default value is 0.
end: This is the last index of the buffer data.
The default value is
Buffer.length.
Example
In the example below, we create a Buffer with the Buffer.from() method. Then, we access the Buffer data and decode the Buffer.
// Create a Bufferconst ourBuffer = Buffer.from("edpresso");// log out Bufferconsole.log(ourBuffer);// decode Bufferconsole.log(ourBuffer.toString())
How to specify encoding
In the code above, we decode our buffer to a string. Note that we do not specify any encoding. Now, let’s specify some encoding.
// Create a Bufferconst ourBuffer = Buffer.from("edpresso");// log out Bufferconsole.log(ourBuffer);// decode Bufferconsole.log(ourBuffer.toString("utf8"))console.log(ourBuffer.toString("utf16le"))console.log(ourBuffer.toString("latin1"))
How to specify start and end parameters
As noted earlier, when the start and end parameters are not provided, the default 0 and Buffer.length are used as the start and end parameters. Hence, we have the complete data when we decode the buffer. Now, let’s specify start and end.
// Create a Bufferconst ourBuffer = Buffer.from("edpresso");// log out Bufferconsole.log(ourBuffer);// decode Buffer but only first 3 data of Bufferconsole.log(ourBuffer.toString("utf8", 0, 3))