You could do:
var token = "ewphOiAiMDA4MDc4ODg4NjU4OTM2IiwKYjogIlJFQSIKfQ==";
eval('var decoded = ' + Buffer.from(token, 'base64').toString());
console.log(decoded.a);
But eval
is extremely dangerous if the base64-encoded string can come from somewhere that is outside your control. An arbitrary string could expand to some unexpected JavaScript that would cause eval
to do something that would make your program misbehave or breach security.
It would be better to express the original object as a JSON string (use JSON.stringify
to do that) and base64-encode that string. Then you can use JSON.parse
to reconstruct the original object without taking on the risk of using eval
. Like this:
var obj = { x: "foo", y: 123 };
var obj_json = JSON.stringify(obj);
// obj_json is '{"x":"foo","y":123}'
var obj_b64 = Buffer(obj_json).toString('base64');
// obj_b64 is 'eyJ4IjoiZm9vIiwieSI6MTIzfQ=='
var decoded = JSON.parse(Buffer.from(obj_b64, 'base64').toString());
console.log(decoded.x);