Skip to content

Latest commit

Β 

History

History
63 lines (43 loc) Β· 2.45 KB

File metadata and controls

63 lines (43 loc) Β· 2.45 KB

prefer-uint8array-base64

πŸ“ Prefer Uint8Array#toBase64() and Uint8Array.fromBase64() over atob(), btoa(), and Buffer base64 conversions.

🚫 This rule is disabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ’‘ This rule is manually fixable by editor suggestions.

atob() and btoa() operate on β€œbinary strings”, so they cannot round-trip Unicode text without workarounds. Node's Buffer base64 conversions work, but tie you to Buffer.

The Uint8Array base64 methods operate on real binary data and are available everywhere Uint8Array is. Prefer Uint8Array.fromBase64() and Uint8Array#toBase64() instead.

Note

Buffer.from(string, 'base64') returns a Buffer, while Uint8Array.fromBase64(string) returns a plain Uint8Array. The fix is offered as a suggestion since the result type differs.

Examples

// ❌
const bytes = atob(base64);

// ❌
const bytes = Buffer.from(base64, 'base64');

// βœ…
const bytes = Uint8Array.fromBase64(base64);
// ❌
const base64 = buffer.toString('base64');

// βœ…
const base64 = buffer.toBase64();

To convert text instead of binary data, encode it first:

// ❌
const base64 = btoa(text);
const text = atob(base64);

// βœ…
const base64 = new TextEncoder().encode(text).toBase64();
const text = new TextDecoder().decode(Uint8Array.fromBase64(base64));

The base64 methods support the base64url alphabet too:

// ❌
const bytes = Buffer.from(base64url, 'base64url');

// βœ…
const bytes = Uint8Array.fromBase64(base64url, {alphabet: 'base64url'});

Tip

The uint8array-extras package offers stringToBase64 and base64ToString helpers for the text case.