Leo Jiang
Leo Jiang

Reputation: 26085

What's the proper way of terminating a Node.js server request?

I'm playing around with a basic Node.js server (no frameworks). I want the server to terminate the request under certain conditions. What's the proper way of doing this? I tried request.connection.destroy(), req.removeListener('data'), and req.removeListener('end'), but the server keeps going and returns results. Here's part of what I have:

http.createServer(function(req,res){
    req.on('data',function(data){
        content+=data;
        if(condition){
            req.connection.destroy();
            req.removeListener('data');
            req.removeListener('end');
        }
    });

    req.on('end',function(){=
        res.writeHead(200,{
            'Context-Type':'text/plain',
        });
        res.write(content);
        res.end();
    });
});

P.S. Isn't it better to do req.once('end',...) instead of req.on('end',...)? Everyone one else seems to use on(), is there a reason for that?

Edit: I changed the if body to:

                req.abort();
                req.connection.destroy();
                req.removeAllListeners('data');
                req.removeAllListeners('end');

However, the end event is still being called (i.e. content is still being written).

Upvotes: 0

Views: 364

Answers (2)

matthewk
matthewk

Reputation: 1841

You should call req.abort();

Documentation here: https://nodejs.org/api/http.html#http_request_abort

Upvotes: 1

OKey
OKey

Reputation: 182

You must return any result. This is only proper way. Your client send request to server so it need to answer. It can be status 400 but it has to be. In the other way your client will never realize that request has been terminated and slow down your app.

Upvotes: 0

Related Questions