Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IncomingMessage abort event

I have this basic express (4.13.3) server in Node (4.2.3).

//blah blah initialization code

app.put('/', function(req, res) {

  req.on('close', function() {
    console.log('closed');
  });

  req.on('end', function() {
    console.log('ended');
  });

  req.on('error', function(err) {
    console.log(err);
  });

  res.send(200);
});

Then I simulate file upload using cURL like this:

curl http://localhost:3000/ -X PUT -T file.zip

It starts uploading (although nothing happens with it) and when it ends, event end fires.

The problem starts when I abort the upload with Ctrl+C. No event fires at all. Nothing happens.

req object inherits from IncomingMessage, thus inherits from Readable, Stream and EventEmitter.

Is there any event at all to catch such an abort? Is there any way to know if the client aborts file upload?

First edit:

User @AwalGarg proposed req.socket.on('close', function(had_error) {}) but I'm wondering if there is any solution to this which is not using sockets?

like image 948
Are Avatar asked Dec 09 '15 13:12

Are


1 Answers

Your code sets up some event listeners, then sends the response back to the client right away, thereby completing the HTTP request prematurely.

Moving res.send() inside the event handlers, keeps the connection open until one of those events takes place.

app.put('/', function(req, res) {

  req.on('close', function() {
    console.log('closed');
    res.send(200);
  });

  req.on('end', function() {
    console.log('ended');
    res.send(200);
  });

  req.on('error', function(err) {
    console.log(err);
    res.send(200);
  });

});
like image 192
Nocturno Avatar answered Nov 05 '22 22:11

Nocturno