Course contentsShow
← JavaScript
Lesson 2358 of 2,72348. Working with Binary DataFree lesson

Encoding Binary Data (ArrayBuffer) to Base64

Convert ArrayBuffer or Uint8Array to Base64 using manual iteration or modern APIs in both browser and Node.

Encoding Binary Data (ArrayBuffer) to Base64

You'll learn how to transform raw binary data (like ArrayBuffer or Uint8Array) into Base64 strings using both browser and Node.js approaches.

The Core Challenge

You've seen btoa() work with strings, but what about actual binary data like image files, audio buffers, or encrypted bytes stored in an ArrayBuffer? You can't just pass an ArrayBuffer directly to btoa() — it expects a string. You need to first convert the bytes to a format btoa() understands.

Browser Approach: Manual Iteration

The classic technique loops through your binary data, converts each byte to a character, then feeds that string to btoa():

function arrayBufferToBase64(buffer) {
  const bytes = new Uint8Array(buffer);
  let binary = '';
  for (let i = 0; i < bytes.length; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}

// Usage with binary data
const buffer = new Uint8Array([72, 101, 108, 108, 111]).buffer;
const base64 = arrayBufferToBase64(buffer);
console.log(base64); // "SGVsbG8="

This builds a binary string character-by-character, where each character represents one byte.

Node.js Approach: Buffer API

Node's Buffer makes this much simpler since it natively supports Base64:

function arrayBufferToBase64Node(buffer) {
  return Buffer.from(buffer).toString('base64');
}

const buffer = new Uint8Array([72, 101, 108, 108, 111]).buffer;
const base64 = arrayBufferToBase64Node(buffer);
console.log(base64); // "SGVsbG8="

Buffer handles the entire conversion internally — no manual iteration needed.

Key Takeaway: Convert ArrayBuffer to Base64 by first creating a Uint8Array view, iterating to build a binary string for btoa() in browsers, or using Buffer.from().toString('base64') in Node.js.