Dotcomtunisia
Dotcomtunisia

Reputation: 123

Sending multiple responses with the same response object in nodejs

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

Upvotes: 3

Views: 3599

Answers (2)

risyasin
risyasin

Reputation: 1321

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

Upvotes: 4

s.d
s.d

Reputation: 29436

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.

Upvotes: 3

Related Questions