To decode a base64 encoded JSON object string in Node.js, you can use the Buffer
module’s Buffer.from
method to convert the base64 encoded string to a buffer, and then use the JSON.parse
method to parse the buffer into a JavaScript object.
Here’s an example:
const base64EncodedJsonString = 'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ==';
// Convert the base64 encoded string to a buffer
const buffer = Buffer.from(base64EncodedJsonString, 'base64');
// Parse the buffer into a JavaScript object
const jsonObject = JSON.parse(buffer);
console.log(jsonObject); // { sub: '1234567890', name: 'John Doe', iat: 1516239022 }
Note that the Buffer.from
method is available in Node.js 6.0.0 and later. If you’re using an older version of Node.js, you can use the new Buffer
constructor instead:
const buffer = new Buffer(base64EncodedJsonString, 'base64');