Base64 encode/decode in Nodejs and Javascript

This article shows how you can base64 encode and decode string using both Nodejs and Javascript.

Javascript: Base64 encode/decode string

Encode String

btoa() function creates a base-64 encoded ASCII string from the given String object.


var encodedData = window.btoa("Hello World!");
console.log(encodedData); // output: SGVsbG8gV29ybGQh

Decode String

atob() function decoded the base-64 encoded string.


var encodedData = "SGVsbG8gV29ybGQh";
var decodeData = window.atob(encodedData);
console.log(decodedData); // output: Hello World!

Nodejs: Base64 encode/decode string

Node.js uses Buffer object to encode/decode string. Buffer is a global object. Hence, we don’t have to include/require it separately. It’s available by default.

Encode String


let data = "Hello World!";
let encodedData = Buffer.from(data).toString('base64')
console.log(encodedData); // output: SGVsbG8gV29ybGQh

Decode String


let data = "SGVsbG8gV29ybGQh"; // encoded data
let decodedData = Buffer.from(data, 'base64').toString('ascii'); // output string in ascii character encoding. utf8 & other encoding can also be used
console.log(decodedData); // output: Hello World

Hope this helps. Thanks.