Base64 in Javascript
In JavaScript, Base64 is a method used to encode binary data into ASCII text format. It is widely used in web development for tasks such as transferring data over the internet or storing data in text files. JavaScript provides built-in functions for encoding and decoding data in Base64 format, making it easy for developers to use this method in their projects. In this page, we will discuss how to use Base64 in JavaScript and provide examples of its practical applications.
Encoding
Encoding to Base64 in JavaScript is simple with the built-in Buffer.from method. To encode a string, simply pass it as the first argument to Buffer.from with an optional encoding type as the second argument (default is "utf-8").
1
2
3
const str = "Hello, world!";
const encoded = Buffer.from(str).toString("base64");
console.log(encoded); // SGVsbG8sIHdvcmxkIQ==
Decoding
To decode a base64 string in JavaScript, you can use the Buffer class which provides a built-in method Buffer.from() to convert the base64 string to a Buffer object. Then, you can use the toString() method on the Buffer object to convert it to a regular string.
1
2
3
4
const base64String = 'SGVsbG8sIHdvcmxkIQ==';
const bufferObj = Buffer.from(base64String, 'base64');
const decodedString = bufferObj.toString('utf8');
console.log(decodedString); // Output: "Hello, world!"
Deprecated atob & btoa
It's worth noting that while atob() and btoa() are widely supported in browsers, they are actually deprecated in Node.js. Instead, you should use the Buffer class or a third-party library for base64 encoding and decoding in Node.js. That being said, you may still come across code that uses atob() and btoa() in Node.js, but it's recommended to switch to using Buffer or a third-party library for better compatibility and security.
1
2
3
4
5
6
7
const originalString = "Hello, world!";
const encodedString = btoa(originalString);
console.log(encodedString); // "SGVsbG8sIHdvcmxkIQ=="
const base64String = "SGVsbG8sIHdvcmxkIQ==";
const decodedString = atob(base64String);
console.log(decodedString); // "Hello, world!"