Question

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");
Was it helpful?

Solution 2

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

OTHER TIPS

To complete @ladenedge's comment for clarity reasons:

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

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top