Vasyl Boroviak
Vasyl Boroviak

Reputation: 6128

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?

Upvotes: 9

Views: 11177

Answers (1)

Vasyl Boroviak
Vasyl Boroviak

Reputation: 6128

The JSON.parse can accept Buffer instances.

const buffer = Buffer.from('{"a":1}')
const obj = JSON.parse(buffer)

Upvotes: 13

Related Questions