Skip to content

Instantly share code, notes, and snippets.

@chiro-hiro
Created November 12, 2020 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chiro-hiro/8b0e87b40216896845013a7169e8e57d to your computer and use it in GitHub Desktop.
Save chiro-hiro/8b0e87b40216896845013a7169e8e57d to your computer and use it in GitHub Desktop.
TypeScript trick to make base64 work on both browser and Node.js
function strToUint8Array(v: string): Uint8Array {
const buf = new Uint8Array(v.length);
for (let i = 0; i < v.length; i += 1) {
buf[i] = v.charCodeAt(i);
}
return buf;
}
function bufferToUint8Array(v: Buffer): Uint8Array {
const buf = new Uint8Array(v.length);
for (let i = 0; i < v.length; i += 1) {
buf[i] = v[i];
}
return buf;
}
export function encodeBase64(v: string | Uint8Array): string {
// eslint-disable-next-line no-undef
return typeof btoa === 'function' ? btoa(v) : Buffer.from(v).toString('base64');
}
export function decodeBase64(v: string): Uint8Array {
return typeof atob === 'function'
? // eslint-disable-next-line no-undef
Uint8Array.from(strToUint8Array(atob(v)))
: bufferToUint8Array(Buffer.from(v, 'base64'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment