Last updated on July 26, 2023
In Node.js, you can easily encode and decode strings to/from Base64 using the built-in Buffer
class. Here’s how you can do it:
Encoding a String to Base64:
const originalString = "Hello, this is a string to encode in Base64.";
// Convert the string to Base64
const encodedString = Buffer.from(originalString).toString('base64');
// Output the Base64 encoded string
console.log("Base64 Encoded String:", encodedString);
Decoding a Base64 String back to the original String:
const base64String = "SGVsbG8sIHRoaXMgaXMgYSBzdHJpbmcgdG8gZW5jb2RlIGluIEJhc2U2NC4=";
// Convert the Base64 string back to the original string
const decodedString = Buffer.from(base64String, 'base64').toString('utf-8');
// Output the decoded string
console.log("Decoded String:", decodedString);
In the encoding example, the Buffer.from()
method is used to convert the original string to a Buffer
object, and then the toString('base64')
method is called to get the Base64 encoded string.
In the decoding example, the Buffer.from()
method is used again, but this time with the base64
encoding argument, to convert the Base64 string back to a Buffer
object. Then, the toString('utf-8')
method is called on the Buffer
object to get the original decoded string.
Keep in mind that if the Base64 string contains invalid characters or is not correctly padded, you may encounter errors during decoding. It’s important to handle such scenarios properly in your code.