#Request.body.getReader() into Uint8Array typed array

10 messages · Page 1 of 1 (latest)

signal briar
#

is it possible to convert a readableStream into a Uint8Array ?

#

the way i am doing it now is to write a file and then read it as Uint8Array


    ensureFileSync(s_path);

    const reader = o_request?.body?.getReader();
    
    // await Deno.writeTextFile(s_path, "test");
    const f = await Deno.open(s_path, {
      create: true,
      write: true,
    });

    await Deno.copy(readerFromStreamReader(reader), f);
    await f.close();
    let o_stat = await Deno.stat(s_path); 
    console.log(o_stat);

    const file = await Deno.open(s_path);
    const p = 0; // your position
    await Deno.seek(file.rid, p, Deno.SeekMode.Start);
    
    const buf = new Uint8Array(o_stat.size); // you can read more and then access a particular slice of the buffer
    const bytesRead = await file.read(buf);
    console.log(bytesRead);
    console.log(buf);
#

i found out that i can do it this way

    let o_array_buffer = await o_request?.arrayBuffer();
    let a_n_iu8 = new Uint8Array(o_array_buffer, 10);
#

but i dont get why my Uint8Array has a length of 118...

Uint8Array(118) [
   75,  76,  77,  78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,
   90,  91,  92,  93,  94,  95,  96,  97,  98,  99, 100, 101, 102, 103, 104,
  105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,  65,  66,  67,
   68,  69,  70,  71,  72,  73,  74,  75,  76,  77,  78,  79,  80,  81,  82,
   83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,  96,  97,
   98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
  113, 114, 115, 116,  65,  66,  67,  68,  69,  70,
  ... 18 more items
]
lilac loom
#

I agree with having utility for that (read all contents from ReadableStream)

#

though I'm not sure if we should overload it to readAll

grim forge
lilac loom
lilac loom
#

(The answer to the original question)
@signal briar I think you can use new Uint8Array(await o_request.arrayBuffer())