将缓冲区转换为JavaScript中的可读字符串?
为此,请使用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
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