1

i am using an express node server and i want to receive response in chunks at client. but i am receiving concatenated data like i have a loop a at server end and at each index i am doing res.write(index) like this

    for(let index = 0; index <= 10; index+){
       res.write(index)
    }

but instead of getting single index at client each time i get a response it contains all previous responses concatenated as well for example for first time i get 1.for second time i get 12.third time i get 123 and so on. at client i am receiving res like this

    axios.post(url, body, {
        onDownloadProgress: progressEvent => {
        const dataChunk = progressEvent.currentTarget.response;
        //chunky response here
        //here i am getting concatenated data
    );
        },
        timeout: 600000
    })
        .then((response) => {
              //final response here
             })
  • maybe try `res.send(index)` – Dorian B Mar 30 '21 at 07:53
  • i did but i think it sends the final response because the second time i do res.send(index) it says headers cannot be set after res has already been sent or something like this. – faisal anwar Mar 30 '21 at 07:56
  • 1
    Try using `res.flush(index)` You can read more here [Send data in chunks](https://stackoverflow.com/questions/45849147/send-data-in-chunks-with-nodejs) – Package.JSON Mar 30 '21 at 07:59

1 Answers1

1

The server's stream can aggregate the chunks in any way it sees fit, and the client is free to buffer them as well, so you will not get per-message semantics this way. See this SO question for an example of what other trouble you may encounter: How to flush chunks of arbitrary sizes in NodeJS

If you are looking to send separate messages to the client, you have several options:

  • Use a streamable data format, such as YAML (with document separators) or XML (and a streaming parser on the client)
  • Use a more suitable protocol: Server-Sent Events or WebSocket
  • Use a cross-transport messaging library such as socket.io
Robert Kawecki
  • 2,218
  • 1
  • 9
  • 17