3

I have a long running process which needs to send data back at multiple reponse. Is there some way to send back multiple responses with express.js I want have "test" after 3 seconde a new reponse "bar"

app.get('/api', (req, res) => 
{
    res.write("test");
    setTimeout(function(){   
        res.write("bar"); 
        res.end();
    }, 3000);
});

with res.write a wait a 3050 of have a on response

t

Stamos
  • 3,938
  • 1
  • 22
  • 48
Dotcomtunisia
  • 123
  • 1
  • 9
  • You can use async, promise all – Puneet Dec 31 '18 at 09:42
  • Possible duplicate of [Sending multiple responses with the same response object in Express.js](https://stackoverflow.com/questions/25209073/sending-multiple-responses-with-the-same-response-object-in-express-js) – Sreehari Dec 31 '18 at 09:49
  • as far as I can remember is there only one response for one request if you use HTTP – HubballiHuli Dec 31 '18 at 11:00

2 Answers2

4

Yes, you can do it. What you need to know is actually chunked transfer encoding.

This is one of the old technics used a decade ago, since Websockets, I haven't seen anyone using this.

Obviously you only need to send responses in different times maybe up to some events will be fired later in chunks. This is actually the default response type of express.js.

But there is a catch. When you try to test this, assuming you are using a modern browser or curl which all of them buffer chunks, so you won't be seeing expected result. Trick is filling up chunk buffers before sending consecutive response chunks. See the example below:

const express = require('express'),
app = express(),
port = 3011;

app.get('/', (req, res) => {

    // res.write("Hello\n"); 
    res.write("Hello" + " ".repeat(1024) + "\n"); 

    setTimeout(() => {
        res.write("World");
        res.end();
    }, 2000);

});

app.listen(port, () => console.log(`Listening on port ${port}!`));

First res.write with additional 1024 spaces forces browser to render chunk. Then you second res.write behaves as you expected. You can see difference with uncommenting the first res.write.

On network level there is no difference. Actually even in browser you can achieve this by XHR Object (first AJAX implementation) Here is the related answer

risyasin
  • 1,325
  • 14
  • 24
3

An HTTP request response has one to one mapping. You can return HTTP response once, however long it may be. There are 2 common techniques:

  1. Comet responses - Since Response is a writable stream, you can write data to it from time to time before ending it. Ensure the connection read timeout is properly configured on the client that would be receiving this data.

  2. Simply use web sockets - These are persistent connection that allow 2 way messaging between server and client.

S.D.
  • 29,290
  • 3
  • 79
  • 130