base64
Convert Uint8Array to base64 string.
code:mod.ts
export function encode (buf: Deno.Buffer): string {
const arr = Array.from(buf.bytes()).map(c => '' + c)
return btoa(arr.reduce((data: string, byte: string) => {
return data + String.fromCharCode(+byte)
}, ''))
}
code:mod.ts
export function decode (str: string): Uint8Array {
const rawStr = atob(str)
const arr = new Uint8Array(new ArrayBuffer(rawStr.length))
for (let i = 0; i < rawStr.length; i++) {
arri = rawStr.charCodeAt(i)
}
return arr
}
実行例
$ deno run https://scrapbox.io/api/code/daiiz-deno/base64/demo.ts
https://i.gyazo.com/971073a1b2f7b3b872a2296bcceff820.png
code:demo.ts
import { encode, decode } from 'https://scrapbox.io/api/code/daiiz-deno/base64/mod.ts'
const ui8 = new Uint8Array(137, 80, 78, 71, 13, 10, 26, 10)
const encodedStr = encode(new Deno.Buffer(ui8))
console.log('encoded:', encodedStr)
console.log('decoded:', decode(encodedStr))
#Examples