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

时间:2019-03-07 10:47:40

标签: javascript node.js typescript buffer

这是将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>
-您如何将其转换为此“缓冲区”字符串的常规值?

我尝试过:

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

3 个答案:

答案 0 :(得分:1)

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

//app.get('/func.js', function(req, res) { res.sendFile(__dirname + "/assets/js" + "/func.js"); });

结果:

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
     )
}

答案 1 :(得分:0)

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

console.log('' + bufferOne)

答案 2 :(得分:0)

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

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