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).

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github