Javascript-如何将缓冲区转换为字符串? [英] Javascript - How to convert buffer to a string?
本文介绍了Javascript-如何将缓冲区转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是将String转换为Buffer然后再返回String的示例:
This is example of converting String to a Buffer and back to String:
let bufferOne = Buffer.from('This is a buffer example.');
console.log(bufferOne);
// Output: <Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e>
let json = JSON.stringify(bufferOne);
let bufferOriginal = Buffer.from(JSON.parse(json).data);
console.log(bufferOriginal.toString('utf8'));
// Output: This is a buffer example.
现在想象有人只给您这个字符串作为起点:
<缓冲区54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e>
-您将如何转换
Now imagine someone just give you only this string as a starting point:
<Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e>
- how would you convert it to regular value of this 'buffer' string?
我尝试过:
let buffer = '<Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e>'
json = JSON.stringify(buffer);
console.log(json);
给出的输出:
"<Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e>"
推荐答案
没有原生方法,但是我写了一个示例为您提供的方法:
No native way for that, but I wrote a sample method for you:
function bufferFromBufferString(bufferStr) {
return Buffer.from(
bufferStr
.replace(/[<>]/g, '') // remove < > symbols from str
.split(' ') // create an array splitting it by space
.slice(1) // remove Buffer word from an array
.reduce((acc, val) =>
acc.concat(parseInt(val, 16)), []) // convert all strings of numbers to hex numbers
)
}
结果:
const newBuffer = bufferFromBufferString('<Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e>')
> newBuffer
<Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e>
> newBuffer.toString()
'This is a buffer example.'
这篇关于Javascript-如何将缓冲区转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文