0

I'm trying to send multiple responses to client while computing. Here is my example:

app.get("/test", (req, res) => {
    console.log('test');
    
    setTimeout(() => {
        res.write('Yep');
        setTimeout(() => {
            res.write('Yep');
            setTimeout(() => {
                res.write('Yep');
                setTimeout(() => {
                    res.write('Yep');
                    setTimeout(() => {
                        res.write('Yep');
                        setTimeout(() => {
                            res.end();
                        }, 1000);
                    }, 1000);
                }, 1000);
            }, 1000);
        }, 1000);
    }, 1000);
    
    
});

I want to get the response in every seconds. But my code works and it send response on end(). Is there any way to do it?

sundowatch
  • 3,012
  • 3
  • 38
  • 66
  • Most http clients, particularly Ajax in browsers will NOT process partial responses as they arrive. Instead, they will collect the entire response and only notify the client when the data is finally all there. So, if you trying to get the client to respond to little pieces of the response as you send them, that's not very likely to be supported in a browser. With non-browser, http clients, you could do it. – jfriend00 Jan 15 '21 at 01:49
  • If you explain what end problem you're really trying to solve, then we could perhaps help you better. For example, a webSocket or socket.io connection might be a better option where you can send individual messages from server to client whenever you want and the client can receive and process each one separately. – jfriend00 Jan 15 '21 at 01:51

1 Answers1

1

You can't send more than one response to a request, that's not how HTTP works. You can send headers more than once (see this answer), but only one response body. You could use websockets or build logic into the client to hit an endpoint every X seconds, if you need functionality like that.

Zac Anger
  • 6,983
  • 2
  • 15
  • 42
  • This question isn't sending more than one response. It's sending multiple pieces of one response. – jfriend00 Jan 15 '21 at 01:49
  • Right, but OP is asking how to fix the code to make it send each of those `Yep`s separately, which isn't possible. – Zac Anger Jan 15 '21 at 01:50
  • `res.write()` WILL send them separately. The issue is that many clients (in particular Ajax clients in the browser) will wait until they've collected the whole response before they make any of it available so you don't get each individual piece as it arrives. – jfriend00 Jan 15 '21 at 02:49
  • Right — but again, the question wasn't asking about writing parts of one response on an interval, it was asking about sending more than one response per request. I should've been clearer in my previous comment ("send" vs "send a whole response with"). – Zac Anger Jan 15 '21 at 02:58