16

How do I create a base64 JSON encoded strings in nodejs?

I tried this and it didn't work.

var buff = new Buffer({"hello":"world"}).toString("base64");

Is this it?

var buff = new Buffer(JSON.stringify({"hello":"world"})).toString("base64");
2
  • 5
    Looks like you've asked and answered your own question here... Commented Mar 19, 2014 at 18:39
  • 2
    Buffer accepts either an integer, an array or a string. But not an object. If you want an object to be converted to JSON, you have to do this explicitly, just like you did in your second example. nodejs.org/api/buffer.html Commented Mar 19, 2014 at 18:40

3 Answers 3

23

To complete @ladenedge's comment for clarity reasons:

var buff = Buffer.from(JSON.stringify({"hello":"world"})).toString("base64")
Sign up to request clarification or add additional context in comments.

Comments

20
var buff = new Buffer(JSON.stringify({"hello":"world"})).toString("base64");

2 Comments

The constructor has since been deprecated. Use Buffer.from() in Node v6 and higher.
This is nice, but why for crying out load the result of btoa({"hello":"world"}) is totally different, i would expect them to be the same
1

You can always prettify above code by providing some spacing, so that when some one decode it back to JSON String it would look good.

var buff = Buffer.from(JSON.stringify({"hello":"world"},undefined,n)).toString("base64")

n = 1 to 10 (Spacing)

Comments

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.