1

In the following example I'm fetching 2 raw bytes.

fetch('https://www.random.org/cgi-bin/randbyte?nbytes=2')
    .then(response=>response.body.getReader())
    .then(reader=>0/*Here convert to Uint16*/)

Any idea how to convert the resulting readable stream Uint16 integer from using 2 bytes?

AnArrayOfFunctions
  • 3,452
  • 2
  • 29
  • 66
  • Once you [got the reader](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader), just [`read()`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader/read) from it? – Bergi Jan 31 '19 at 22:49
  • 2
    Btw, it's probably much easier to read the response body [into an array buffer](https://developer.mozilla.org/en-US/docs/Web/API/Body/arrayBuffer) than to use a readable stream reader. – Bergi Jan 31 '19 at 22:52

1 Answers1

1

If you are sure that you get all needed bytes in the first chunk, then you can try this:

fetch('https://www.random.org/cgi-bin/randbyte?nbytes=2')
    .then(response=>response.body.getReader())
    .then(reader => reader.read())
    .then(result => console.log(new DataView(result.value.buffer).getUint16()));

See ReadableStreamDefaultReader.read(), Uint8Array, and DataView.

Or a simpler way:

fetch('https://www.random.org/cgi-bin/randbyte?nbytes=2')
    .then(response => response.arrayBuffer())
    .then(buffer => console.log(new DataView(buffer).getUint16()));
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26