ReadableStream with source binary of different data kind?

49 views Asked by At

I'm downloading some binary files that are expected to be read as Uint16Array.

I would like to use a ReadableStream so that I can start consuming the data before all of it has downloaded, but I'm having a problem with the data kind because ReadableStream assumes the data will be a UInt8Array and doesn't seem to allow me to specify a different kind.

This is my code so far:

const reader = response.body?.getReader();

if (reader == null) throw new Error("Failed to get reader from response body");

const readableStream = new ReadableStream({
  start(controller) {

    return pump();

    async function pump() {
      const { done, value } = await reader.read();
      // When no more data needs to be consumed, close the stream
      if (done || value == null) {
        controller.close();
        return;
      }

      // Enqueue the next data chunk into our target stream
      controller.enqueue(value);

      return pump();
    }
  },
});

const decompressionStream = new DecompressionStream("gzip");

// gzip compression
const decompressedStream = readableStream.pipeThrough(decompressionStream);

if (decompressedStream == null) {
  throw new Error("Failed to pipe through decompression stream");
}


const reader = decompressedStream.getReader();
const readChunk = async () => {
  const { done, value } = await reader.read();
  if (done || value == null) {
    return;
  }

  console.log(Uint16Array.from(value));
  readChunk();
}
readChunk();

This errors out during the decompression with Uncaught (in promise) RangeError: byte length of Uint16Array should be a multiple of 2.

I suppose the issue is that the data should be read as Uint16Array and then decompressed, but it's actually reading it as Uint8Array.

What can I do?

0

There are 0 answers