• Node.js Video Tutorials

Node.js - Buffer.toString() Method



The NodeJS Buffer.toString() method helps to decode the string as per the encoding given. By default, the encoding used is 'utf-8'.

Syntax

Following is the syntax of the Node.JS Buffer.toString() Method

buf.toString([encoding[,start[,end]]])

Parameters

This method accepts three parameters but all are optional. The same is explained below.

  • encoding − (optional)The encoding to be used. The default encoding used is utf-8.

  • start − (optional) The start index at which the decoding will start. The default value is 0.

  • end − (optional) The end index at which the decoding will end. The default value is buffer.length.

Return value

The method buffer.toString() decodes the buffer with the encoding given and returns the string.

Example

To create a buffer, we are going to make use of NodeJS Buffer.from() method −

const buffer = Buffer.from('Hello');
console.log(buffer.toString('hex'));

Output

The encoding used is 'hex'. The string hello used will be decoded into hex encoding. On executing the above program, it will generate the following output −

48656c6c6f

Example

In this example let us use the start and end offset values to decode the string.

When start/end offset values are used, the portion of the string decoded is returned.

const buffer = Buffer.from('Hello World');
console.log(buffer.toString('hex', 2, 6));

Output

6c6c6f20

Example

In this example will make use of Buffer.alloc() and fill it with a value.

const buffer = Buffer.alloc(10);
buffer.fill('H');
console.log(buffer.toString('hex'));

Output

48484848484848484848
nodejs_buffer_module.htm
Advertisements