← Public packages
@kentcdodds/dropbox
Upload, share, and manage Dropbox files via OAuth — small or large uploads and direct download URLs.
src/base64.ts
29 lines · 911 B · TypeScript/** Decode a base64 string to bytes. Throws if the input is not valid base64. */
export function decodeBase64(value: string): Uint8Array {
let binary: string
try {
binary = atob(value)
} catch {
throw new Error('bytesBase64 must be valid base64.')
}
const bytes = new Uint8Array(binary.length)
for (let index = 0; index < binary.length; index += 1) {
bytes[index] = binary.charCodeAt(index)
}
return bytes
}
/** Encode bytes to a base64 string. */
export function encodeBase64(bytes: Uint8Array): string {
const chunks: string[] = []
const chunkSize = 0x8000
for (let index = 0; index < bytes.length; index += chunkSize) {
chunks.push(String.fromCharCode(...bytes.subarray(index, index + chunkSize)))
}
return btoa(chunks.join(''))
}
/** Encode a UTF-8 string to base64. */
export function encodeTextBase64(value: string): string {
return encodeBase64(new TextEncoder().encode(value))
}