Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support decoding data URL in Node < v16 #3

Merged
merged 1 commit into from
Jun 29, 2022
Merged

fix: support decoding data URL in Node < v16 #3

merged 1 commit into from
Jun 29, 2022

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
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants