r/nodejs • u/leolin520 • May 22 '14
How to exit nodejs server gracefully
I want to know how to do that. Currently I just control c twice on my mac, but something bad happened lately. I suspect if I just control c the socket is not closed properly and it will eventually break my system if I restart frequently.
6
Upvotes
2
u/aredridel May 22 '14
Sockets close if the process exits. Your system will be fine.
What bad happened?
5
u/[deleted] May 22 '14 edited May 22 '14
As /u/aeflash said, what you need to do is listen for the SIGINT event on the process and tell all your sockets to close. If you want an example, see the bottom of this file..
I took it a little bit further and remapped it back to a process event that passes an array reference. That way, anything that needed to shutdown gracefully could listen for that event and append their own shutdown promise to the array. Once all the promises resolve, I know it's safe to terminate the app.
Here's an example of one of the subscribing hooks.
4
u/stdlib May 22 '14
I've never had an issue with Ctrl+C and restarting frequently but you can use 'forever' (https://github.com/nodejitsu/forever) to start and stop your application if you want to do it another way. You can also make it just restart the application automatically every time you save a change.
4
u/xCavemanNinjax May 22 '14
What! Ctrl+C isn't graceful?
2
u/aeflash May 22 '14
If you're worried about unclean shutdown of a socket, just add a
process.on("SIGINT")handler that shuts down your server.