Will this behave similar to node's Buffer.toString('base64')?
joeythomaschaske opened this issue · 13 comments
I've used node's buffer class before and it makes for very easy use of converting buffers to different formatted strings. Will this follow node's already existing example?
https://nodejs.org/api/buffer.html#buftostringencoding-start-end
It will not look like .toString('base64'), but the goal is to make it similarly easy to convert a buffer to a base64 string, yes.
Will it work with multibyte characters? An issue I've run into in the past is using the Crypto class to generate secure bits creates non unicode characters which don't convert well to base64 using TextEncoder/TextDecoder and atob/btoa
window.crypto.getRandomValues(new Uint8Array(12));
I'm currently using the answer suggested here to correctly handle the conversion to base64
I'm looking forward to this being added if it handles those characters correctly!
The issue does not come up - ArrayBuffers (and Uint8Arrays) can only contain bytes, which have a well-defined mapping to and from base64. The problem with atob is that its input type (String) can contain non-byte values, but that's not an issue here.
This proposal doesn't handle conversion of bytes to/from Unicode, which is the place you need to think about multi-byte characters.
I like the API that node provides. Passing the encoding as a string opens the ability to add other encodings later. For example, Node added bas64url later, which is a different, but standardized version of base64.
With this proposal, this would need a new method: buffer.toBase64Url() instead of buffer.toFoo("base64url").
Adding new methods is no more difficult than adding new valid string arguments, and is much more discoverable, so I am not inclined to use Node's design here.
The choice of alphabet for base64, i.e. base64Url support, will be handled by an option to the base64 method; see the readme or the playground.
It will not look like
.toString('base64'), but the goal is to make it similarly easy to convert a buffer to a base64 string, yes.
Why not support .toString('base64') and .from(input, 'base64') in order to be consistent with Buffer?
Regardless, it is established.
On node’s Buffer, which is generally avoided in modern node code in favor of Typed Arrays.
I favor property based feature detection. Having toString('future-format') fall through to the behavior of toString() in existing implementations would be a hazard.
(Though, I will note that crypto APIs hide their supported hashing algorithms, for example, behind string-enums which is also a precedent and not consistent with my preference for property based feature detection.)
@kriskowal to be fair, .toString.length could be used to check that, but I still agree with you.
Closing as answered.