ExpressJS: How to know when a request has finished?
Asked Answered
C

3

10

In an ExpressJS set up on top of NodeJS, I have a bit of code like this:

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);
});

The code is wrote like that for simplicity (if anyone wants the real code I'm happy to post it in some pastebin).

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

The problem is that when I exit curl, the loop keeps on going forever. How do I tell express or nodejs that it's supposed to end that loop (with clearInterval I guess) as soon as the request has ended ?

Coagulate answered 15/8, 2011 at 8:19 Comment(0)
V
14

req.on("close")

So simply

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);
    });
});
Vanillin answered 15/8, 2011 at 8:47 Comment(2)
@JoaoPintoJeronimo you will find that the express req and res objects extend the native HTTPRequest and HTTPResponse objects in node.js core. So fall back on those methodsVanillin
No longer works in Express 4, see my post. In a nutshell, use on-finished middleware.Expressionism
E
12

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

Expressionism answered 9/9, 2015 at 0:55 Comment(1)
This is no longer true, or at least req.on('close', ...) is still indirectly referenced on the Express 4.x documentation. "The req object is an enhanced version of Node’s own request object and supports all built-in fields and methods."Balcony
N
2

With express 4.X it is req.on("end", () => {}), it is better to add this as a express middleware.

Yeah but on-finished npm package works too.

Nonbelligerent answered 15/11, 2019 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.