0
0
Node.jsframework~5 mins

Buffer to string conversion in Node.js

Choose your learning style9 modes available
Introduction
Buffers hold raw data in Node.js. Converting a buffer to a string lets you read or show that data as text.
When you receive data from a file and want to read it as text.
When you get data from a network request and need to display it.
When you want to convert binary data into readable text for logging.
When working with streams that provide data as buffers but you want strings.
When decoding data from different character encodings like UTF-8 or ASCII.
Syntax
Node.js
buffer.toString([encoding], [start], [end])
encoding defaults to 'utf8' if not specified.
start and end let you convert only part of the buffer.
Examples
Convert the entire buffer to a UTF-8 string (default).
Node.js
const str = buffer.toString();
Convert the buffer to a string using ASCII encoding.
Node.js
const str = buffer.toString('ascii');
Convert only the first 5 bytes of the buffer to a UTF-8 string.
Node.js
const str = buffer.toString('utf8', 0, 5);
Sample Program
This program creates a buffer from a string, then converts it fully and partially back to strings. It prints both results.
Node.js
const buffer = Buffer.from('Hello, Node.js!');
const fullString = buffer.toString();
const partialString = buffer.toString('utf8', 0, 5);
console.log(fullString);
console.log(partialString);
OutputSuccess
Important Notes
Buffers store raw bytes, so converting with the wrong encoding can show strange characters.
Always specify encoding if you know the data is not UTF-8 to avoid errors.
Partial conversion is useful when you want only a slice of the data.
Summary
Buffers hold raw data; toString() converts it to readable text.
Default encoding is UTF-8 but you can specify others like ASCII or base64.
You can convert the whole buffer or just a part of it.