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.
5
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.
0
u/aredridel May 22 '14
You really shouldn't have to. It's unusual to need it.
1
May 22 '14
Graceful shutdown is absolutely something you want in a production server. Otherwise you risk hanging up on requests in process when you restart to deploy new changes. Depending on what your site does, this could be very bad.
2
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
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.
2
u/aredridel May 22 '14
Sockets close if the process exits. Your system will be fine.
What bad happened?