Ask coding questions

← Back to all posts
Graceful shutdown in node
h
kaldisberzins (260)

In the official node documentation it gives a way to fire an event when the server is shutting down. Something along the lines of

process.on('exit', (code) => {
  console.log(`About to exit with code: ${code}`);
});

I gave this a go in this repl and it does not fire any event. At least, nothing is logged to the console. Also, for some reason this same code in a node.js repl instead of an express repl will just immediately log the return and stop. Connections still work, but there is no restart, only start. Any ideas on either of these?

Edit

I added a function bound to multiple possible events that could be fired on exit and made it write to a file to eliminate the possibility of the event firing but the console getting cleared immediately. Nothing appears in the file. I'm stumped. Any ideas?

Edit 2

Pressed ^C in the console and that worked for some reason. It didn't stop the server however, it still was serving the page.

Commentshotnewtop
Geocube101 (246)

You may be able to manually close the server using io.server.close(). Once done, you can manually destroy all connections with socket.destroy() where socket is the socket of the connected client

kaldisberzins (260)

@Geocube101 I am not using socket.io. I am talking about the node server. process.exit() will stop the server. That I know. However, it seems like repl.it uses something else. I would like to be able to bind an event to whatever they use.