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?
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?
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With