How to find the base64 of a string in JavaScript

How to find the base64 of a string in JavaScript:

In this post, we will learn different ways to encode/decode a string to base64 in JavaScript. Base64 is a way of encoding binary data to ASCII text. It takes binary data and encodes it to ASCII text for easy transmission.

Base64 is widely used for transmitting and storing binary data in ASCII format. It is a common algorithm, i.e. you can encode it in your JavaScript browser and send the data to a python server and the server can decode it.

Each Base64 digit represents 6 bits of data. So, if we are encrypting three 8 bits bytes or 24 bits of a file, we need 4 Base64 digits to encode it completly 4 * 6 = 24. So, the Base64 encoded string will be at least 133% of the size of the source.

btoa and atob methods:

JavaScript provides two methods to do a base64 encoding and decoding. These are btoa and atob.

btoa:

btoa method takes one binary string and converts it to a Base64 encoded string. We can use this method to do a Base64 encryption.

It takes one parameter, i.e. the string to encode. It returns an ASCII string that is the Base64 representation of the string.

It can throw InvalidCharacterError if there is a character in the string that doesn’t fit in a single byte.

javascript btoa example

atob:

atob method decodes a Base64 encoded string. It takes the string as the parameter and returns the decoded data.

It takes one parameter, i.e. the binary string holding the Base64 value. It returns one ASCII string that holds the decoded data.

It can throw InvalidCharacterError for an invalid Base64 string.

For example,

JavaScript atob example

How to do Base64 encoding/decoding in Nodejs:

In Nodejs, we can’t use btoa and atob. in a Nodejs application. There is another class called Buffer. This class is used to create fixed length sequence of bytes and this class also provides a way to do Base64 encoding/decoding.

Note that Buffer also provides other popular formats as well like utf-8, ASCII, hex, base64url etc.

It is easy to do encode/decode using Buffer. We can use toString(‘base64’) to encode a buffer object to Base64 and from(data, ‘base64) to decode it back.

For example,

import {Buffer} from 'buffer';

const original = 'Hello !';

const base64 = Buffer.from(original).toString('base64');

const decoded = Buffer.from(base64, 'base64').toString('utf-8');

console.log('Original: ',original);
console.log('Encoded: ',base64);
console.log('Decoded: ',decoded);

It will print:

Original:  Hello !
Encoded:  SGVsbG8gIQ==
Decoded:  Hello !

You might also like: