【问题标题】:Javascript - How to convert buffer to a string?Javascript - 如何将缓冲区转换为字符串?
【发布时间】:2019-07-29 05:32:58
【问题描述】:

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

现在假设有人只给你这个字符串作为起点:
&lt;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&gt;
- 你如何将它转换为这个“缓冲区”字符串的常规值?

我试过了:

   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>"

【问题讨论】:

  • 你的预期输出是什么?
  • 你的意思是转换成JSON?已经是字符串了?
  • 你的缓冲区变量已经是一个字符串了!
  • 我正在尝试将“字符串缓冲区值”从缓冲区转换为字符串。
  • 添加了工作时的示例,我需要做同样的事情,但从字符串开始......

标签: javascript node.js typescript buffer


【解决方案1】:

实现此目的的另一种方法:

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'
  );

【讨论】:

    【解决方案2】:

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

    console.log('' + bufferOne)
    

    【讨论】:

    • 这并没有真正回答问题。我知道它已经是字符串,但他需要按照最佳答案状态进行(从类似缓冲区字符串的表示形式转换为字符串)。
    • 更好用toString
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 1970-01-01
      • 2016-03-09
      • 2016-09-23
      • 1970-01-01
      相关资源
      最近更新 更多