how to properly close node-express server?

前端 未结 4 1232
孤街浪徒
孤街浪徒 2020-12-08 01:35

I need to close server after getting callback from /auth/github/callback url. With usual HTTP API closing server is currently supporting with s

相关标签:
4条回答
  • 2020-12-08 02:08

    If any error occurs in your express app then you must have to close the server and you can do that like below-

    var app = express();
    var server = app.listen(process.env.PORT || 5000)
    

    If any error occurs then our application will get a signal named SIGTERM

    You can read more about node signal here-

    https://www.gnu.org/software/libc/manual/html_node/Termination-Signals.html

    process.on('SIGTERM', () => {
      console.info('SIGTERM signal received.');
      console.log('Closing http server.');
      server.close(() => {
        console.log('Http server closed.');
      });
    });
    
    0 讨论(0)
  • 2020-12-08 02:11

    In express v3 they removed this function.

    You can still achieve the same by assigning the result of app.listen() function and apply close on it:

    var server = app.listen(3000);
    server.close()
    

    https://github.com/visionmedia/express/issues/1366

    0 讨论(0)
  • 2020-12-08 02:22

    app.listen() returns http.Server. You should invoke close() on that instance and not on app instance.

    Ex.

    app.get(
        '/auth/github/callback',
        passport.authenticate('github', { failureRedirect: '/login' }),
        function(req, res) {
            res.redirect('/');
    
            setTimeout(function () {
                server.close();
                // ^^^^^^^^^^^
            }, 3000)
        }
    );
    
    var server = app.listen('http://localhost:5000/');
    

    You can inspect sources: /node_modules/express/lib/application.js

    0 讨论(0)
  • 2020-12-08 02:22

    I have answered a variation of "how to terminate a HTTP server" many times on different node.js support channels. Unfortunately, I couldn't recommend any of the existing libraries because they are lacking in one or another way. I have since put together a package that (I believe) is handling all the cases expected of graceful express.js HTTP(S) server termination.

    https://github.com/gajus/http-terminator

    The main benefit of http-terminator is that:

    • it does not monkey-patch Node.js API
    • it immediately destroys all sockets without an attached HTTP request
    • it allows graceful timeout to sockets with ongoing HTTP requests
    • it properly handles HTTPS connections
    • it informs connections using keep-alive that server is shutting down by setting a connection: close header
    • it does not terminate the Node.js process
    0 讨论(0)
提交回复
热议问题