Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 982
Itération 122442 Avatar asked Mar 08 '19 08:03

Itération 122442


People also ask

How do I convert a buffer to a readable string?

Buffers have a toString() method that you can use to convert the buffer to a string. By default, toString() converts the buffer to a string using UTF8 encoding. For example, if you create a buffer from a string using Buffer. from() , the toString() function gives you the original string back.

Can you JSON parse a buffer?

Buffers can convert to JSON. The JSON specifies that the type of object being transformed is a Buffer , and its data.

How do I decode a buffer in Node JS?

In Node. js, the Buffer. toString() method is used to decode or convert a buffer to a string, according to the specified character encoding type. Converting a buffer to a string is known as encoding, and converting a string to a buffer is known as decoding.


2 Answers

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.

like image 162
Mark Avatar answered Nov 13 '22 22:11

Mark


Try

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

This will convert [object Object] as a string

like image 3
Aravin Avatar answered Nov 13 '22 22:11

Aravin