9

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?

2
  • Interested. hackernoon.com/…. Commented Apr 30, 2018 at 10:14
  • @AjAX. The code by your link creates an intermediate string. I'm looking for a way to avoid any intermediate strings (or any other intermediate data). Commented Apr 30, 2018 at 11:31

1 Answer 1

13

The JSON.parse can accept Buffer instances.

const buffer = Buffer.from('{"a":1}')
const obj = JSON.parse(buffer)
Sign up to request clarification or add additional context in comments.

7 Comments

That’s what said in the link.
@AjAX. Nope. The link does not say so.
This: console.log(JSON.parse(Buffer.from('{"a":1}'))) prints this: { a: 1 } in node.js v4 or later. Looks like you are using TypeScript, not JavaScript.
Unfortunately, it still converts the buffer to string under the hood: stackoverflow.com/a/66994351/1202251
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.