Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert a string to type Uint8Array in nodejs

  • 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
like image 258
Arran Duff Avatar asked Jul 10 '20 17:07

Arran Duff


2 Answers

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

like image 108
Patrick Roberts Avatar answered Oct 13 '22 00:10

Patrick Roberts


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.

like image 34
Octo Poulos Avatar answered Oct 12 '22 22:10

Octo Poulos