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


When converting object to base64 I was getting out of latin range issues and character invalid error.

I made it work in my project with the below line.

Include the base64 and utf8 node packages and access them like this:

var bytes = base64.encode(utf8.encode(JSON.stringify(getOverviewComments())));

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