NodeJS JavaScript -如何将buffer转换为字符串?

u5rb5r59  于 2023-06-29  发布在  Node.js
关注(0)|答案(4)|浏览(176)

这是一个将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.

现在假设有人只给予你这个字符串作为起点:
<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>

  • 如何将它转换为这个'buffer'字符串常规值?
    我试过:
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>"
nwwlzxa7

nwwlzxa71#

没有原生的方法,但我为你写了一个示例方法:

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.'
polkgigr

polkgigr2#

与空字符串串联时自动转换:

console.log('' + bufferOne)
4zcjmb1e

4zcjmb1e3#

实现这一点的另一种方法:

function toBuffer(bufferString) {
  const hex = bufferString.match(/\s[0-9a-fA-F]+/g).map((x) => x.trim());
  return Buffer.from(hex.join(''), 'hex');
}

const buffer = '<Buffer 49 20 6c 6f 76 65 20 79 6f 75>';
const actualBuffer = toBuffer(buffer);

console.log(buffer); // <Buffer 49 20 6c 6f 76 65 20 79 6f 75>
console.log(actualBuffer); // <Buffer 49 20 6c 6f 76 65 20 79 6f 75>
console.log(actualBuffer === buffer); // false
console.log(actualBuffer.toString()); // Secret message

相同的函数,不同的语法:

const toBuffer = (bufferString) =>
  Buffer.from(
    bufferString
      .match(/\s[0-9a-fA-F]+/g)
      .map((x) => x.trim())
      .join(''),
    'hex'
  );
vdzxcuhz

vdzxcuhz4#

你不能做一个缓冲模板,但是如果你从某个地方得到了一个数字数组,你就可以立即给予一个数字数组。
至少你让事情变得更难了

const ListToBuffer = (list) => Buffer.from(list.join(''), 'hex');

相关问题