Read a large response in chunks as it arrives

Viewed 100

I have a node js server that executes an exe file that outputs data in chunks:

function requestHandler(request, response)
{
  childproc = process.spawn("exefile");

  childproc.stdout.on("data", (data) =>
  {
    response.write(data);
  });

  childproc.on("exit", (code) =>
  {
    response.end();
  });
}

And its being received by a javascript client:

const xhr = new XMLHttpRequest();
...
xhr.send(...)
xhr.onreadystatechange = function ()
{
  if(xhr.readyState == XMLHttpRequest.LOADING)
  {
    // I can see this being called as and when the server is writing the data,
    // but ofcourse since the response has not ended, I get null when I try
    // xhr.response;
  }

  if (xhr.readyState == XMLHttpRequest.DONE)
  {
    response = xhr.response; // its an array buffer, by the way
  }
}

Is there a nice way to get the data as and when it comes without waiting for the entire thing to be ended? One way is to keep ending the response after each chunk on the server side, but I will then have to initiate multiple requests (as many as 10K requests) to get all the chunks, seems like I am missing some cool and easy way.

0 Answers
Related