Created
November 12, 2020 03:44
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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