How convert a string to type Uint8Array in nodejs

Viewed 5327
  • 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
4 Answers
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.

Why not simply using:

const resEncodedMessage = new TextEncoder().encode(message)

This is how I do it when grabbing a string

   var myString = "[4,12,43]"
   var stringToArray = myString.replace('[', '').replace(']', '').split(',');
   var stringToIntArray = Uint8Array.from(stringToArray );
   console.log(stringToIntArray);

Related