Here’s the translation of the Base64 Encoding example from Go to JavaScript, formatted in Markdown suitable for Hugo:
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:
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.