Javascript - How to convert buffer to a string?
Asked Answered
B

4

15

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>"
Bainbridge answered 7/3, 2019 at 10:47 Comment(5)
What is your expected output?Robbery
you mean convert to JSON? It is already a string?Paramagnet
Your buffer variable is already a string!Palatinate
I am trying to convert that 'string buffer value' from a buffer to a string.Bainbridge
Added example when is working and I need to do the same but starting from a String...Bainbridge
R
7

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.'
Revulsion answered 7/3, 2019 at 12:35 Comment(0)
T
10

Automatically converted when concatenated with an empty string:

console.log('' + bufferOne)
Twentyone answered 2/11, 2020 at 14:31 Comment(2)
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).Achromatin
Better use toStringPyromancy
R
7

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.'
Revulsion answered 7/3, 2019 at 12:35 Comment(0)
P
0

Another method of achieving this:

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

Same function, different syntax:

const toBuffer = (bufferString) =>
  Buffer.from(
    bufferString
      .match(/\s[0-9a-fA-F]+/g)
      .map((x) => x.trim())
      .join(''),
    'hex'
  );
Pyromancy answered 2/6, 2021 at 21:34 Comment(0)
B
0

you can not make a buffer template, but immediately give an array of numbers if you took them from somewhere.

At least you're making it harder.

const ListToBuffer = (list) => Buffer.from(list.join(''), 'hex');
Baggage answered 28/6, 2023 at 14:58 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.