HTTP Response Streaming - JavaScript Receiving data as 1 big chunk or packet instead of in pieces

222 views Asked by At

I am trying to stream a HTTP Response from the web server and read each chunk of data from the stream on the JavaScript side. The JavaScript side is receiving all of the data as 1 chunk or packet instead of in pieces like I want.

  • Here is the Rust code:
use std::convert::Infallible;
use async_stream::stream;
use actix_web::{get, HttpResponse};
use actix_web::web::Bytes;

#[get("/stream")]
pub async fn stream() -> HttpResponse {

    HttpResponse::Ok()
        .streaming(stream! {
            let mut count = 0;
            while count < 10 {
                yield Ok::<_, Infallible>(Bytes::from(count.to_string()));
                count += 1;
            }
        })

}
  • Here is the Javascript code:
async function get_stream() {
    const response = await fetch('/stream');
    const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();

    while (true) {
        let {value, done} = await reader.read();
        if (done) break;
        console.log('Received', value);
    }

    console.log('Response fully received');
}

This is what I am receiving in the Console:

Received 0123456789
stream.js:69 Response fully received

This is the result I'm trying to receive in the console:

Received 0
Received 1
Received 2
Received 3
Received 4
Received 5
Received 6
Received 7
Received 8
Received 9
stream.js:69 Response fully received
0

There are 0 answers