Base64 Encoding in JavaScript

Here’s the translation of the Base64 Encoding example from Go to JavaScript, formatted in Markdown suitable for Hugo:

// This syntax imports the `btoa` and `atob` functions for base64 encoding/decoding
// These functions are available globally in browsers, but we're using Node.js syntax here
const { btoa, atob } = require('buffer');

// Here's the string we'll encode/decode
const data = "abc123!?$*&()'-=@~";

// JavaScript provides built-in support for standard base64 encoding/decoding
// Here's how to encode using the standard encoder
const sEnc = btoa(data);
console.log(sEnc);

// Decoding is straightforward in JavaScript
const sDec = atob(sEnc);
console.log(sDec);
console.log();

// For URL-compatible base64, we need to replace some characters
function urlEncode(str) {
    return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}

function urlDecode(str) {
    str = str.replace(/-/g, '+').replace(/_/g, '/');
    while (str.length % 4) str += '=';
    return atob(str);
}

// This encodes/decodes using a URL-compatible base64 format
const uEnc = urlEncode(data);
console.log(uEnc);
const uDec = urlDecode(uEnc);
console.log(uDec);

JavaScript provides built-in support for base64 encoding/decoding through the btoa() and atob() functions. These functions are available globally in browsers, but for Node.js environments, we need to import them from the buffer module.

The standard base64 encoding is straightforward using btoa() for encoding and atob() for decoding.

For URL-compatible base64 encoding, JavaScript doesn’t have built-in support. However, we can create custom functions that modify the output of btoa() to make it URL-safe, and reverse these modifications before using atob() for decoding.

To run this program, save it as base64-encoding.js and use Node.js:

$ node base64-encoding.js
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

The string encodes to slightly different values with the standard and URL-compatible base64 encoders (trailing + vs -), but they both decode to the original string as desired.