johni johni - 1 year ago 116
Node.js Question

Base64 encode a javascript object

I have large Javascript objects which I would like to encode to base-64 for AWS Kinesis`
It turns out that:

let objStr = new Buffer(JSON.stringify(obj), 'ascii');
new Buffer(objStr, 'base64').toString('ascii') !== objStr

I'm trying to keep this as simple as possible.

How can I base-64 encode JSON and safely decode it back to its original value?


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 = new Buffer(objJsonStr).toString("base64");