Open In App

Node.js Buffer.toString() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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.

Syntax:

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.

Example 1:




// Node.js program to demonstrate the   
// Buffer.toString() Method  
        
// Creating a buffer 
var buffer = new Buffer.alloc(5);
   
// Loop to add value to the buffer
for (var i = 0; i < 5; i++) {
    buffer[i] = i + 97;
}
   
// Display the value of buffer
// in string format
console.log(buffer.toString());
console.log(buffer.toString('utf-8', 1, 4));
console.log(buffer.toString('hex'));


Output:

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’.

Example 2:




// Node.js program to demonstrate the   
// Buffer.toString() Method  
        
// Creating a buffer 
var buffer = new Buffer.alloc(5);
   
// Loop to add value to the buffer
for (var i = 0; i < 5; i++) {
    buffer[i] = i + 97;
}
   
// Display the value of buffer
// in string format
console.log(buffer.toString(undefined));


Output:

abcde

Note: The above program will compile and run by using the node index.js command.

Reference: https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end



Last Updated : 13 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads