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.
Buffer.toString( encoding, start, end )
encoding
: This is the format in which the buffer data has to be encoded. The encodings supported by Node.js include utf8
, utf16le
, and latin1
.
uft8
is the default ifencoding
is 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
.
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())
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"))
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))