Heyo. Trying to convert a `Uint8Array` into a utf-...
# javascript
s
Heyo. Trying to convert a
Uint8Array
into a utf-8 string. Anyone know the best practice way to do this, since a
Uint8Array
isn't back by a
UByteArray
internally (from what I can tell) ?
t
s
Could use the
TextDecoder
from JS yeah, just not sure how to instantiate it from Kotlin with the js
new
syntax.
t
Copy code
val encoder = TextEncoder()
s
TextEncoder
has to be defined somewhere as
External
no? And it's constructor?
Or you mean just create it something like
Copy code
fun TextDecoder(): dynamic = js("new TextDecoder()")
?
t
Copy code
external class TextEncoder() {
   // required methods
}
Works?
s
Can't use
TextDecoder
apparently, my
Uint8Array
is too large and
TextDecoder('utf-8').decode(bytes)
fails with
RangeError: Maximum call stack size exceeded in json object.
Seeking other alternatives now.. I might have to chunk this or something.
What is kotlin-js doing when I call
println("bytes: $bytes")
where
bytes
is an
Uint8Array
and it prints out a nice utf-8 encoded string in my console, but when I call
bytes.toString()
it prints out
[...]
? Doesn't embedding something in a string just call its
toString()
internally? Not sure how I could be getting different behavior when I call it manually.
e
"bytes: $bytes"
==
"bytes: " + bytes
which Kotlin translates to exactly that in JS. this leads JS to coerce
bytes
to a
String
, which results in the decoding behavior you see
whereas
.toString()
goes through Kotlin's stringification implementation which treats
Array
specially, and
Uint8Array
is an
Array
a workaround:
(arr.asDynamic().toString)().unsafeCast<String>()
will call JS's
.toString()
, not Kotlin's
👍 1
t
"$bytes"
?
e
K/JSIR appears to compile that to
'' + bytes
, so that would work too, I'm not sure how documented/futureproof that is though
s
Thanks for the workaround! Got it working 🙂
t
FYI -
TextDecoder
generated and will be available in next release of wrappers
265 Views