How to properly close Node Express server?

Sometimes, we we want to properly close Node Express server.

In this article, we’ll look at how to properly close Node Express server.

How to properly close Node Express server?

To properly close Node Express server, we can call the close method.

For instance, we write

const server = app.listen(3000);

//...

server.close((err) => {
  console.log('server closed')
  process.exit(err ? 1 : 0)
})

to call server.close with a callback that has the error err parameter.

If err is set, then there’s an error when closing the Express server and we call process.exit with exit code 1.

Otherwise, we call process.exit with exit code 0.

Conclusion

To properly close Node Express server, we can call the close method.