How to Encode and Decode Base 64 String in Node JS



Encoding and decoding a string in Base 64 ins Javascript or Node JS isn’t as trivial as it seems, but below there is a simple solution to do this:


The solution use the Buffer object to convert the String to Base 64.

To encode the string in Base64, use the Buffer toString('base64') function to encode the string.

To decode the Base64 string, use the Buffer from(string, 'base64') function to decode the Base64 string.


const string = 'Hello, World!';
console.log('Original string: ' + string);

// encode the string
const encoded = Buffer.from(string).toString('base64');
console.log('Encoded: ' + encoded);

// decode the string
const decoded = Buffer.from(encoded, 'base64');
console.log('Decoded: ' + decoded)


Original string: Hello, World!
Encoded: SGVsbG8sIFdvcmxkIQ==
Decoded: Hello, World!


Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.