encodeDecodeBase64Strictly
JavaScript
// Strict Base64 helpers for UTF-8 text and Uint8Array byte data.
const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
export function encodeBase64(input) {
if (typeof input !== 'string' && !(input instanceof Uint8Array)) {
throw new TypeError('input must be a string or Uint8Array');
}
const bytes = typeof input === 'string' ? Buffer.from(input, 'utf8') : input;
return Buffer.from(bytes).toString('base64');
}
export function decodeBase64(text, { as = 'text' } = {}) {
if (typeof text !== 'string') throw new TypeError('Base64 input must be a string');
const compact = text.replace(/\s+/g, '');
if (!BASE64.test(compact)) throw new SyntaxError('Invalid Base64 input');
const bytes = Buffer.from(compact, 'base64');
if (bytes.toString('base64') !== compact) {
throw new SyntaxError('Invalid or non-canonical Base64 input');
}
return as === 'bytes' ? bytes : bytes.toString('utf8');
}