How can I do Base64 encoding in Node.js?

Better Stack Team
Updated on March 11, 2024

In Node.js, you can use the built-in Buffer class to perform Base64 encoding and decoding. The Buffer class provides methods for encoding and decoding data in various formats, including Base64.

Here's an example of how to perform Base64 encoding:

 
// Convert a string to Base64
const originalString = 'Hello, this is a string to encode!';
const base64String = Buffer.from(originalString).toString('base64');

console.log('Original String:', originalString);
console.log('Base64 Encoded:', base64String);

In this example:

  • The Buffer.from(originalString) method creates a Buffer object from the original string.
  • The toString('base64') method converts the Buffer object to a Base64-encoded string.

If you want to decode a Base64 string back to its original form, you can use the following:

 
// Convert a Base64 string back to the original string
const decodedString = Buffer.from(base64String, 'base64').toString('utf-8');

console.log('Base64 Decoded:', decodedString);

In this example:

  • The Buffer.from(base64String, 'base64') method creates a Buffer object from the Base64-encoded string.
  • The toString('utf-8') method converts the Buffer object to a UTF-8 encoded string, representing the original string.

These methods are synchronous. If you're working with asynchronous code or need to handle binary data in streams, you may want to explore additional methods provided by the Buffer class or consider using third-party libraries such as base64url or btoa (for browsers).