Skip to content

Commit 4e56724

Browse files
committed
feat(string): support TextEncoder for converting to base64
`TextEncoder` along with `<Uint8Array>.toBase64` works only in the browser but does not use Node.js' Buffer.
1 parent e322c96 commit 4e56724

1 file changed

Lines changed: 13 additions & 1 deletion

File tree

packages/utils/src/string/base64.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,19 @@ import { Buffer } from 'node:buffer'
55
* @param str - The input string encoded in utf-8.
66
* @returns - The base64 encoded string.
77
*/
8-
export const toBase64 = (str: string): string => Buffer.from(str, 'utf-8').toString('base64')
8+
const _toBase64Buffer = (str: string): string => Buffer.from(str, 'utf-8').toString('base64')
9+
10+
/**
11+
* Encode a given UTF-8 string to bytes.
12+
*
13+
* @param {string} str - The input string.
14+
* @returns {Uint8Array} - bytes
15+
*/
16+
export const toBase64 = (str: string): string =>
17+
// `.toBase64` is only available in browsers (but Buffer is not, since it is Node.js API).
18+
typeof TextEncoder !== 'undefined' && typeof new Uint8Array().toBase64 !== 'undefined'
19+
? new TextEncoder().encode(str).toBase64()
20+
: _toBase64Buffer(str)
921

1022
/**
1123
* Decode the given base64 string.

0 commit comments

Comments
 (0)