-
Notifications
You must be signed in to change notification settings - Fork 0
/
base64.ts
38 lines (36 loc) · 995 Bytes
/
base64.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Convert from binary to base64 encoded string.
* @example
* ```ts
* const bin = await Deno.readFile("./file");
* const encode = b64Encode(bin);
* const decode = b64Decode(encode);
* ```
*/
export function b64Encode(data:Uint8Array):string{
return btoa([...data].map(v => String.fromCharCode(v)).join(""));
}
/**
* Convert from base64 encoded string to binary.
* @example
* ```ts
* const bin = await Deno.readFile("./file");
* const encode = b64Encode(bin);
* const decode = b64Decode(encode);
* ```
*/
export function b64Decode(data:string):Uint8Array{
return new Uint8Array([...atob(data)].map(v => v.charCodeAt(0)));
}
/**
* Convert from binary to base64 encoded DataURL.
* Default MIME type is `application/octet-stream`.
* @example
* ```ts
* const bin = await Deno.readFile("./file");
* const data = b64DataURL(bin);
* ```
*/
export function b64DataURL(data:Uint8Array, type?:string):string{
return `data:${type ?? "application/octet-stream"};base64,${b64Encode(data)}`;
}