How to Base64 Encode/Decode a String in Node.js

Base64 encoding is used when there is a need to encode binary data, especially when that data needs to be stored and transferred over media designed to deal with text.

Base64 Encoding

To encode a string in Base64 in Node.js, you can use the Buffer.from().toString(‘base64’) method.

Here is the step-by-step guide to encode base64 string in Node.js.

  1. Create a new Buffer instance from the string you want to encode.
  2. Use the toString() method to convert the Buffer instance to a base64 string.
const str = "Jawan Movie";

const base64Encoded = Buffer.from(str).toString('base64');

console.log(base64Encoded);

Output

SmF3YW4gTW92aWU=

Base64 Decoding

To decode a Base64-encoded string to a plain string in Node.js, use the Buffer.from(encodedString, ‘base64’).toString(‘utf-8’) method.

const encodedString = "SmF3YW4gTW92aWU=";

const plainString = Buffer.from(encodedString, 'base64').toString('utf8')

console.log(plainString);

Output

Jawan Movie

The primary use case of Base64 encoding is when binary data, such as images or video, needs to be sent over email or used in web-based data formats like JSON or XML.