How can I do Base64 encoding in Node.js?

To perform Base64 encoding and decoding in Node.js, you can use the built-in Buffer class. Below is a detailed guide with examples for different scenarios:

1. Basic String Encoding/Decoding

Encode a String to Base64

const text = "Hello World!";
const encodedText = Buffer.from(text, 'utf8').toString('base64');
console.log(encodedText); // SGVsbG8gV29ybGQh

Decode a Base64 String

const base64String = "SGVsbG8gV29ybGQh";
const decodedText = Buffer.from(base64String, 'base64').toString('utf8');
console.log(decodedText); // Hello World!

2. File Encoding/Decoding

Encode a File to Base64

const fs = require('fs');

// Read file into a Buffer
const fileBuffer = fs.readFileSync('image.jpg');

// Convert Buffer to Base64 string
const base64File = fileBuffer.toString('base64');
console.log(base64File); // Base64 string of the image

Decode Base64 and Save as a File

const base64Data = "SGVsbG8gV29ybGQh"; // Replace with actual Base64 string
const decodedBuffer = Buffer.from(base64Data, 'base64');

// Save decoded data to a file
fs.writeFileSync('decoded-image.jpg', decodedBuffer);

3. URL-Safe Base64

Base64 strings often include +, /, and = characters, which are not URL-safe. Replace them as follows:

Encode to URL-Safe Base64

const text = "Data to encode!";
const base64 = Buffer.from(text, 'utf8').toString('base64');

// Replace problematic characters
const urlSafeBase64 = base64
  .replace(/\+/g, '-')
  .replace(/\//g, '_')
  .replace(/=+$/, ''); // Remove padding

console.log(urlSafeBase64); // e.g., RGF0YSB0byBlbmNvZGU

Decode URL-Safe Base64

const urlSafeString = "RGF0YSB0byBlbmNvZGU";

// Revert URL-safe characters and add padding
let base64 = urlSafeString
  .replace(/-/g, '+')
  .replace(/_/g, '/');

// Add padding (required for decoding)
while (base64.length % 4 !== 0) {
  base64 += '=';
}

const decoded = Buffer.from(base64, 'base64').toString('utf8');
console.log(decoded); // Data to encode!

4. Handling Binary Data

Encode/Decode Binary Data

// Encode binary data (e.g., Uint8Array)
const binaryData = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
const base64 = Buffer.from(binaryData).toString('base64');
console.log(base64); // SGVsbG8=

// Decode back to binary
const decodedBuffer = Buffer.from(base64, 'base64');
console.log(decodedBuffer); // <Buffer 48 65 6c 6c 6f>

5. Async File Operations

For large files, use asynchronous methods to avoid blocking the event loop:

const fs = require('fs').promises;

async function encodeFileAsync(filePath) {
  const buffer = await fs.readFile(filePath);
  return buffer.toString('base64');
}

async function decodeAndSaveAsync(base64String, outputPath) {
  const buffer = Buffer.from(base64String, 'base64');
  await fs.writeFile(outputPath, buffer);
}

// Usage
encodeFileAsync('large-file.zip')
  .then(base64 => decodeAndSaveAsync(base64, 'decoded-file.zip'));

Key Notes

  • Padding: The = padding in Base64 is optional for decoding in Node.js, but some systems require it.
  • Character Set: Base64 uses A-Z, a-z, 0-9, +, /, and =.
  • Buffer: The Buffer class handles binary data, and its methods are synchronous. Use streams for very large files.

Summary Table

TaskCode Example
Encode a stringBuffer.from(text, 'utf8').toString('base64')
Decode a stringBuffer.from(base64Str, 'base64').toString('utf8')
Encode a filefs.readFileSync(file).toString('base64')
Decode a filefs.writeFileSync(output, Buffer.from(base64Str, 'base64'))
URL-safe encodeReplace +-, /_, and trim =
URL-safe decodeReplace -+, _/, and add padding

This covers the essentials of Base64 encoding/decoding in Node.js using the Buffer class!

Leave a Reply

Your email address will not be published. Required fields are marked *