15

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");
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • 5
    Looks like you've asked and answered your own question here... – sgress454 Mar 19 '14 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. http://nodejs.org/api/buffer.html – Felix Kling Mar 19 '14 at 18:40

3 Answers3

21

To complete @ladenedge's comment for clarity reasons:

var buff = Buffer.from(JSON.stringify({"hello":"world"})).toString("base64")
vighnesh153
  • 4,354
  • 2
  • 13
  • 27
cpres
  • 953
  • 1
  • 10
  • 13
20
var buff = new Buffer(JSON.stringify({"hello":"world"})).toString("base64");
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • 11
    The constructor has since been deprecated. Use [Buffer.from()](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding) in Node v6 and higher. – ladenedge May 18 '17 at 15:07
  • 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 – Mercury Mar 31 '22 at 20:59
0

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)

Saurabh Talreja
  • 335
  • 2
  • 6