Itération 122442
Itération 122442

Reputation: 2972

Convert buffer to readable string javascript

I receive a JSON as a buffer. I want to parse it into a readable or JSON object.

However, despite all techniques (JSON.stringify(), toString('utf8'), I am not able to get it done.

here is what I have so far:

enter image description here

And here is what it gives me:

enter image description here

How can I transform it into a readable something?

Upvotes: 12

Views: 17280

Answers (3)

Nico Serrano
Nico Serrano

Reputation: 797

If you are comfortable with hexadecimal representation of buffers use:

Buffer.from(val).toString('hex')

Upvotes: 1

Aravin
Aravin

Reputation: 7097

Try

console.log(Buffer.from(val).toString());

This will convert [object Object] as a string

Upvotes: 4

Mark
Mark

Reputation: 92461

Your code is working. The buffer you have is actually the string "[object Object]".

let b = Buffer.from('[object Object]', 'utf8')
console.log(JSON.stringify(b))
// {"type":"Buffer","data":[91,111,98,106,101,99,116,32,79,98,106,101,99,116,93]}

console.log(b.toString('utf8'))
// [Object object]

The problem you need to figure out is why is a buffer with that string being sent. It seems like the sender of the buffer needs to call stringify or otherwise serialize the object before sending it. Then you can turn it back to a string with toString() and use JSON.parse() on the string.

Upvotes: 13

Related Questions