The Express server does not close

advertisements

I'm creating an Express server with reloadable endpoints.
To make this possible I created an endpoint for such a purpose.

But when I call server.close() on the Express's HTTP server it still continues listening, while the server.listening says otherwise, it still is.

Here is a simplified version of my script (Not working fully, but you get the gist):

class simpleServer {
    constructor() {
         let express = require('express');
         this.app = express();
         this.app.get('/reload', this.reload);
         this.server = this.app.listen(3000);
    }

    reload(req, res) {
         console.log('Closing server');             

         this.server.close(function() {
             console.log('Closed server');
         });

         // Re-init & stuff

         res.json({
             message: 'Reloaded'
         });
    }
}

let server = new simpleServer();

When I call the endpoint, the server will output 'Closing server', but the 'Closed server' is not being called. And when I reload the page, it still works, while the server.listening is equal to false.

I'm using Node.js version 6.0.0 with Express version 4.14.0.

Hope I supplied sufficient information.

Thanks

Update: The 'Closed server' does get called, but it took 5 minutes.

Update 2: Fixed the issue by calling req.destroy() after sending the response, does this have any side-effects tho?

Update 3: A cleaner fix would be keeping a record of current connections and closing those in the reload function instead of closing them instantly. This will probably be less heavy if you have a higher load.


When you call .close(), it only stops accepting new connections, it does not terminate existing connections.

The reason it may take some time to actually close is if there are existing connections that have set Connection: keep-alive in case of more requests.