Javascript - How to convert buffer to a string?

前端 未结 2 1575
情歌与酒
情歌与酒 2021-01-13 08:04

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

//          


        
相关标签:
2条回答
  • 2021-01-13 08:21

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

    result:

    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.'
    
    0 讨论(0)
  • 2021-01-13 08:27

    Automatically converted when concatenated with an empty string:

    console.log('' + bufferOne)
    
    0 讨论(0)
提交回复
热议问题