Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert buffer to readable string in JavaScript?
In Node.js, buffers store binary data and need to be converted to strings for readability. The toString() method with encoding parameters handles this conversion.
What is a Buffer?
A Buffer is a Node.js object that represents a fixed-size chunk of memory allocated outside the JavaScript heap. It's used to handle binary data directly.
Basic Buffer to String Conversion
Use the toString() method with the appropriate encoding. UTF-8 is the most common encoding for text data.
// Create a buffer from string
var actualBufferObject = Buffer.from('[John Smith]', 'utf8');
console.log("The actual buffer object:");
console.log(JSON.stringify(actualBufferObject));
// Convert buffer back to string
console.log("Get back the original string:");
console.log(actualBufferObject.toString('utf8'));
The actual buffer object:
{"type":"Buffer","data":[91,74,111,104,110,32,83,109,105,116,104,93]}
Get back the original string:
[John Smith]
Understanding Buffer Data
Each character in the buffer corresponds to its ASCII/UTF-8 code point. Here's how to inspect individual character codes:
var myString = '[John Smith]';
console.log("ASCII code breakdown:");
for (var i = 0; i < myString.length; i++) {
console.log("The ASCII value of '" + myString[i] + "' is = " + myString.charCodeAt(i));
}
ASCII code breakdown: The ASCII value of '[' is = 91 The ASCII value of 'J' is = 74 The ASCII value of 'o' is = 111 The ASCII value of 'h' is = 104 The ASCII value of 'n' is = 110 The ASCII value of ' ' is = 32 The ASCII value of 'S' is = 83 The ASCII value of 'm' is = 109 The ASCII value of 'i' is = 105 The ASCII value of 't' is = 116 The ASCII value of 'h' is = 104 The ASCII value of ']' is = 93
Different Encoding Options
The toString() method supports various encodings:
var buffer = Buffer.from('Hello World', 'utf8');
console.log("UTF-8:", buffer.toString('utf8'));
console.log("Base64:", buffer.toString('base64'));
console.log("Hex:", buffer.toString('hex'));
UTF-8: Hello World Base64: SGVsbG8gV29ybGQ= Hex: 48656c6c6f20576f726c64
Conclusion
Use buffer.toString('utf8') to convert buffers to readable strings. The buffer stores data as byte arrays, with each byte representing a character's ASCII/UTF-8 code point.
