1

I have following stream of Uint8 arrays that I need to convert to singular string. enter image description here

So far I have tried to decode the array using TextDecoderStream, which it does, but it always returns multiple strings instead of one. This is my code:

const textDecoder = new TextDecoderStream();
    port.readable.pipeTo(textDecoder.writable);
    const reader = textDecoder.readable.getReader();
    while (true) {
      const { value, done } = await reader.read();
      if (done) {
        reader.releaseLock();
        break;
      }
      console.log(value);
    }

Any suggestions how to solve this?

Thank you in advance

EDIT: Eventully I managed to get the final string using for loop and join function:

for (let i = 0; i < arrLength; i++) {
  const { value } = await reader.read();
  if (value) {
   arr.push(value);
  }
}
const rfidString = arr.join("");
Adam Šulc
  • 526
  • 6
  • 24
  • In what encoding? Any time you're converting bytes to characters (or vice-versa), you have to consider what text encoding is being used. – T.J. Crowder Sep 27 '22 at 08:49
  • I voted to reopen because [the question used as a dupetarget](https://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript) shows how to do this with an **array** as input, not a stream. The streaming aspect of this seems crucial. – T.J. Crowder Sep 27 '22 at 08:54
  • @T.J.Crowder yes, the steam part is crucial. To answer (kind of) your previous comment - I am fairly new to encoding/decoding so I really don't know. I tried serialport package in my back-end app and that was working just fine, however I need to convert the stream on front-end which is problematic. – Adam Šulc Sep 27 '22 at 08:57
  • What is the serial data? Why do you want a string? – T.J. Crowder Sep 27 '22 at 08:58
  • Well the string is supposed to be some sort of identificator. After I get that string, the front-end send a request so that user can be authenticated. – Adam Šulc Sep 27 '22 at 09:01
  • 1
    If what's being sent is meant to be consumed as text, then the API providing it must say what text encoding that text is being sent in (even if it's just something antiquated like ASCII). Most things working in English and other western scripts these days are UTF-8, but not all, and particularly if it's some kind of embedded device... – T.J. Crowder Sep 27 '22 at 09:34
  • Don't know if that helps, but the device is RFID reader. I am trying to get the data after the user connects his tag to it. – Adam Šulc Sep 27 '22 at 10:00
  • You are right, code edited. – Adam Šulc Sep 27 '22 at 11:29

0 Answers0