Working with node.js or other javascript platforms (multioperability), you'll find that some methods decide to return something different than a string. An Uint8Array is a typed array that represents an array of 8-bit unsigned integers.
The following list of methods , provide a collection of efficient ways to convert an Uint8Array to a regular string in javascript.
Little strings
The following method is acceptable for little arrays (>=100k characters), otherwise you'll get exceptions as RangeError : Maximum call stack size exceeded
or Out of stack space
. However you need to know that this method doesn't play good with UTF-8 characters.
Browser implementation
If your javascript is being executed in a browser, you can make use of the TextEncoder
and TextDecoder
native functions which allow you to choose which codification you want to use. The Encoding API helps solving the string conversion problem.
Crossplatform method
The following method is very useful and works pretty good. It doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments. Works through the UTF-8 convention.
Large blocks
If your data block is huge, you may want to use a method that works properly with huge data (an async method). In this case we'll create blob that contains our Uint8Array and then we'll use the file reader to read it as text.
Note: as said before, this method is recommendable only if you handle huge datasets.
Comments
Post a Comment