Nodejs base64 encode

Base64 encoding in Node.js can be done easily using the Buffer class. Here’s how you can encode data into Base64:

Encoding a String to Base64

You can use the Buffer class to encode a string to Base64 as follows:

Code example:

const str = "Hello, World!";
const base64Encoded = Buffer.from(str).toString('base64');
console.log(base64Encoded); // Output: SGVsbG8sIFdvcmxkIQ==

Decoding a Base64 String

To decode a Base64-encoded string back to its original form:

Code example:

const base64Encoded = "SGVsbG8sIFdvcmxkIQ==";
const decodedStr = Buffer.from(base64Encoded, 'base64').toString('utf-8');
console.log(decodedStr); // Output: Hello, World!

Encoding Binary Data to Base64

If you have binary data (e.g., a file buffer), you can encode it to Base64 as well:

Code example:

const fs = require('fs');
// Read a file into a buffer
const fileBuffer = fs.readFileSync('example.jpg');

// Convert the buffer to a Base64 string
const base64Encoded = fileBuffer.toString('base64');
console.log(base64Encoded);

Decoding Base64 to Binary

To decode a Base64 string back into binary data:

Code example:

const base64Encoded = "base64-encoded-data";
const binaryData = Buffer.from(base64Encoded, 'base64');

// Save binary data to a file
fs.writeFileSync('decoded_example.jpg', binaryData);

Key Points

  • Buffer.from(data): Converts a string or binary data into a Buffer.
  • toString(‘base64’): Encodes the Buffer to a Base64 string.
  • Buffer.from(data, ‘base64’): Decodes a Base64 string back to binary data.
  • Base64 encoding is often used for transmitting binary data as text (e.g., for embedding images or transferring over JSON).

These methods should cover most Base64 encoding and decoding scenarios in Node.js.

Support On Demand!

Node

Related Q&A