30
  • How do I convert a string to a Uint8Array in node?
  • I don't normally develop in Javascript and this is driving me nuts. They offer a conversion Uint8Array.toString() but not the other way around. Does anyone know of an easy way for me to do this without creating my own parser?
  • I have seen some other answers to this, but they don't seem to address this specific class type
Patrick Roberts
52.3k10 gold badges119 silver badges165 bronze badges
asked Jul 10, 2020 at 17:33
1

3 Answers 3

34

You can use Buffer.from(string[, encoding]). The Buffer class has implemented the Uint8Array interface in Node since v4.x. You can also optionally specify an encoding with which to do string processing in both directions, i.e. buffer.toString([encoding]).

answered Jul 10, 2020 at 17:39

Comments

24

Why not simply using:

const resEncodedMessage = new TextEncoder().encode(message)
answered Sep 13, 2022 at 9:24

Comments

15
Uint8Array.from(text.split('').map(letter => letter.charCodeAt(0)));

or (appears about 18% faster):

Uint8Array.from(Array.from(text).map(letter => letter.charCodeAt(0)));

Note: These only work for ASCII, so all the letters are modulo 256, so if you try with Russian text, it won't work.

answered Jun 22, 2021 at 21:13

5 Comments

Answers with explanation of code generally do better than code dumps which leave it to others to interpret. Also, text.split('') doesn't work well for Unicode strings; see How to get character array from a string?
Well you replied just as I was editing the answer. Indeed it's not good for unicode but this method is very simple and fast and might be exactly what he's looking for.
I'd probably just delete that first code snippet as Array.from does respect logical character iteration, and your only issue is charCodeAt, which I would swap to .codePointAt(0) (which can return up to a 32bit number); here you can throw an exception, if you really do expect the codepoints to always be below 512.
Btw, this will always work: Uint8Array.from(encodeURI(text).split(/%|(?<!%.?)/).map((x) => ((x[1]) ? parseInt(x, 16) : x.charCodeAt(x))))
I was just wondering why did you need the array? Cannot you just go straight to Uint8Array.from(text, letter => letter.charCodeAt(0))

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.