Base64 encode a javascript object

From String to Base-64

var obj = {a: 'a', b: 'b'};
var encoded = btoa(JSON.stringify(obj))

To decode back to actual

var actual = JSON.parse(atob(encoded))

For reference look here.

https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding


You misunderstood the Buffer(str, [encoding]) constructor, the encoding tells the constructor what encoding was used to create str, or what encoding the constructor should use to decode str into a byte array.

Basically the Buffer class represents byte streams, it's only when you convert it from/to strings that encoding comes into context.

You should instead use buffer.toString("base64") to get base-64 encoded of the buffer content.

let objJsonStr = JSON.stringify(obj);
let objJsonB64 = Buffer.from(objJsonStr).toString("base64");