Javascript - How to convert buffer to a string?

11,452

Solution 1

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

Solution 2

Automatically converted when concatenated with an empty string:

console.log('' + bufferOne)
Share:
11,452

Related videos on Youtube

Joe
Author by

Joe

Updated on September 15, 2022

Comments

  • Joe
    Joe over 1 year

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

    Now imagine someone just give you only this string as a starting point:
    <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>
    - how would you convert it to regular value of this 'buffer' string?

    I tried with:

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

    Gives 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>"
    
    • Krishna Prashatt
      Krishna Prashatt about 5 years
      Your buffer variable is already a string!
  • Alexander Santos
    Alexander Santos almost 3 years
    This doesn't really replies the question. I know it's already string, but he needs to do as the best answer states (Convert from the Buffer-string-like representation to string).
  • A1rPun
    A1rPun almost 3 years
    Better use toString