วิธีทำ
ใช้ toString('utf8')
ตัวอย่างโค้ด
var actualBufferObject = Buffer.from('[John Smith]', 'utf8');
console.log("The actual buffer object=");
console.log(JSON.stringify(actualBufferObject));
console.log("Get back the original object=");
console.log(actualBufferObject.toString('utf8'));
var myObjectValue = '[John Smith]';
console.log("The data you are getting from the buffer is equal to ASCII code equivalent...");
for (var counter = 0; counter < myObjectValue.length; counter++) {
console.log("The ascii value of " + myObjectValue[counter] + " is =" + (myObjectValue.charCodeAt(counter)));
}
วิธีรัน
node fileName.js
ชื่อไฟล์ demo197.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo197.js
The actual buffer object= {"type":"Buffer","data":[91,74,111,104,110,32,83,109,105,116,104,93]}
Get back the original object= [John Smith]
The data you are getting from the buffer is equal to ASCII code equivalent...
The ascii value of [ is =91
The ascii value of J is =74
... (ASCII values for each character)
คำอธิบาย
Buffer.from(string, 'utf8') สร้าง buffer จาก string encoding utf8buffer.toString('utf8') แปลง buffer กลับเป็น stringcharCodeAt() ได้ ASCII/Unicode code point ของแต่ละ character