13
  • 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
  • 49,224
  • 10
  • 102
  • 153
Arran Duff
  • 1,214
  • 2
  • 11
  • 23

4 Answers4

17

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]).

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
7
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.

Octo Poulos
  • 523
  • 6
  • 5
  • 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?](https://stackoverflow.com/q/4547609/215552) – Heretic Monkey Jun 22 '21 at 21:18
  • 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. – Octo Poulos Jun 22 '21 at 21:20
3

Why not simply using:

const resEncodedMessage = new TextEncoder().encode(message)
Siyavash Hamdi
  • 2,764
  • 2
  • 21
  • 32
-2

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);
Todd Vance
  • 4,627
  • 7
  • 46
  • 66