Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert node.js Buffer to JavaScript object without an intermediate string

I have a Buffer instance which contains utf-8 JSON.

Usually you convert it this way:

const buffer = Buffer.from('{"a":1}')
const str = buffer.toString("utf-8")
const obj = JSON.parse(str)

To make the Buffer->Object conversion more performant how would I convert it without an intermediate string?

like image 401
Vasyl Boroviak Avatar asked Apr 30 '18 10:04

Vasyl Boroviak


People also ask

How do you convert a buffer to a string value in node JS?

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.

How do I decode buffer data 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.

How will you convert a buffer to JSON in node JS?

The Buffer. toJSON() method returns the buffer in JSON format. Note: The JSON. Stringify() is the method which can also be used to return the data in JSON format.

Which method is used to copy sub buffers of a node buffer?

js buffer copy() Method.


1 Answers

The JSON.parse can accept Buffer instances.

const buffer = Buffer.from('{"a":1}')
const obj = JSON.parse(buffer)
like image 113
Vasyl Boroviak Avatar answered Sep 19 '22 13:09

Vasyl Boroviak