ExpressJS: how do I know when a request is completed?

In ExpressJS installed on top of NodeJS, I have this code:

app.get('/keys/readresults/:keyname', basic_auth, function(req,res){
    res.writeHead(200, {'content-type': 'text/json'});
    setInterval(
        go_to_database_and_get('stuff', function (database_replies) {
        res.write(database_replies)
        })
    ,5000);
});

This code is written for simplicity (if someone needs a real code, I am happy to publish it in some pastbin).

What happens when I - this is exactly what I wanted: I get a status header of 200, it checks the database for any results that I want, and writes the response back, then waits 5 seconds and looks for new leads to the database and again records the response, and so on for each interval of 5 seconds.curl -u username:password http://localhost:4000/keys/readresults/key

The problem is that when I exit curl, the loop continues forever. How do I tell express or nodejs that it should have completed this loop (with an explicit clearInterval value) as soon as the request ended?

+5
source share
2 answers

req.on("close")

So simple

app.get('/keys/readresults/:keyname', basic_auth, function(req,res){
    res.writeHead(200, {'content-type': 'text/json'});
    var no = setInterval(
        go_to_database_and_get('stuff', function (database_replies) {
        res.write(database_replies)
    });
    ,5000);
    req.on("close", function() {
        clearInterval(no);
    });
});
+6
source

req.on('close', ...)no longer works in Express 4. Use on-finishedmiddleware.

+4
source

All Articles