Base64 is a way of encoding binary data into text using 64 characters that are common to most encodings and that are also printable. It is useful for transmitting and storing data that might otherwise cause problems for some protocols or systems that are not designed to handle binary data.
You may need to use Base64 encoding when you want to convert binary data into text format for various purposes, such as:
Base64 encoding is not meant to be a secure or efficient way of storing or transmitting data, as it increases the size of the data by about 33% and can be easily decoded by anyone. It is only a way of ensuring that the data can be safely transported across different systems that may have different interpretations of binary data.
Base64 works by dividing the input data into groups of three bytes (24 bits) and then converting each group into four characters from the 64-character alphabet. Each character represents six bits of the input data. If the input data is not a multiple of three bytes, padding characters (=
) are added to make it a multiple of four characters.
btoa()
and atob()
functionsThese are two global functions in JavaScript that can be used to encode and decode data in Base64 format. The atob()
function takes a Base64-encoded string as an argument and returns the original binary string. The btoa()
function does the opposite: it takes a binary string as an argument and returns the Base64-encoded string.
// To encode a string in Base64, use btoa(binaryString)
let encoded = btoa('Hello, world!');
console.log(encoded); // SGVsbG8sIHdvcmxkIQ==
// To decode a Base64 string, use atob(base64String)
let decoded = atob('SGVsbG8sIHdvcmxkIQ==');
console.log(decoded); // Hello, world!
The Buffer
module in Node.js can be used to encode and decode data in Base64 format. Here is an example of how to use it:
// To encode a string in Base64, use Buffer.from(string, 'utf-8').toString('base64')
let encoded = Buffer.from('Hello, world!', 'utf-8').toString('base64');
console.log(encoded); // SGVsbG8sIHdvcmxkIQ==
// To decode a Base64 string, use Buffer.from(string, 'base64').toString('utf-8')
let decoded = Buffer.from('SGVsbG8sIHdvcmxkIQ==', 'base64').toString('utf-8');
console.log(decoded); // Hello, world!
You can also use the Buffer
module to encode and decode binary data, such as images or files, in Base64 format.