Introduction
Buffers hold raw data in Node.js. Converting a buffer to a string lets you read or show that data as text.
Jump into concepts and practice - no test required
buffer.toString([encoding], [start], [end])
const str = buffer.toString();const str = buffer.toString('ascii');
const str = buffer.toString('utf8', 0, 5);
const buffer = Buffer.from('Hello, Node.js!'); const fullString = buffer.toString(); const partialString = buffer.toString('utf8', 0, 5); console.log(fullString); console.log(partialString);
toString() method do when called on a Node.js Buffer?toString() method converts this raw data into a readable string using a specified encoding, defaulting to UTF-8.buf to a string using ASCII encoding?toString() method takes an optional encoding as a string argument inside parentheses.const buf = Buffer.from('48656c6c6f', 'hex');
console.log(buf.toString());toString() without encoding defaults to UTF-8, decoding bytes to 'Hello'.const buf = Buffer.from('hello');
const str = buf.toString(utf8);
console.log(str);buf containing UTF-8 encoded text. How do you convert only the first 5 bytes to a string?toString() method can take encoding, start, and end byte positions.toString('utf8', 0, 5) specifying encoding and byte range.