Skip to content

Conversation

@pastelmind
Copy link
Contributor

I want to publish code that works on Node.js and web browsers alike, and I would like to support Node v14, which reaches EOL on April 2023. However, Node < v16 do not provide a global atob() function for decoding base64 strings, and must use Buffer.from() instead. (See docs for atob())

Furthermore, Buffer.from(str, 'base64').toString() is much faster than atob() in Node:

// Node v16.15.1 > var bigStr = btoa('1234567890abcdefghijklmnopqrstuvwxyz'.repeat(100000)); > console.time('atob'); atob(bigStr); console.timeEnd('atob'); atob: 117.196ms > console.time('Buffer.from'); Buffer.from(bigStr, 'base64').toString(); console.timeEnd('Buffer.from'); Buffer.from: 9.797ms

This is because atob() is intentionally unoptimized. (See rationale)

Thus, we should prefer Buffer.from() whenever it is available.

This PR uses Buffer.from() if it is available, and atob() otherwise. In the rare event that neither exists, the code throws an Error.

Node < v16 do not provide a global `atob()` function for decoding base64 strings, and must use `Buffer.from()` instead. Furthermore, `Buffer.from(str, 'base64').toString()` is much faster than `atob()` in Node. Thus, we should use `Buffer.from()` whenever it is available.
@Menci Menci merged commit 21f71c2 into Menci:main Jun 29, 2022
@pastelmind pastelmind deleted the fix-node14-support branch June 29, 2022 23:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants