ThomasReggi
ThomasReggi

Reputation: 59495

base64 JSON encoded strings in nodejs

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");

Upvotes: 16

Views: 28343

Answers (3)

cpres
cpres

Reputation: 1003

To complete @ladenedge's comment for clarity reasons:

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

Upvotes: 23

Saurabh Talreja
Saurabh Talreja

Reputation: 349

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)

Upvotes: 1

ThomasReggi
ThomasReggi

Reputation: 59495

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

Upvotes: 20

Related Questions