Javascript - 如何将缓冲区转换为字符串?

Joe*_*Joe 9 javascript buffer node.js typescript

这是将 String 转换为 Buffer 再转换回 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.
Run Code Online (Sandbox Code Playgroud)

现在想象一下有人只给你这个字符串作为起点:
<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 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);
Run Code Online (Sandbox Code Playgroud)

给出输出:

"<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>"
Run Code Online (Sandbox Code Playgroud)

小智 9

与空字符串连接时自动转换:

console.log('' + bufferOne)
Run Code Online (Sandbox Code Playgroud)

  • 更好地使用 [`toString`](https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end) (2认同)

小智 6

没有本地方法,但我为您编写了一个示例方法:

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
     )
}
Run Code Online (Sandbox Code Playgroud)

结果:

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.'
Run Code Online (Sandbox Code Playgroud)