I am struggling to intercept the signal when nodemon is restarting my express server. I need this in order to close the database which otherwise throws an error when I try to use it next. EDIT: it didn't look like it at first but it does call some of the functions when I terminate it via Ctrl+C. I've commented which ones.
Apparently, nodemon sends the SIGUSR2 signal when it is restarting, but I tried adding an event to that as well as countless others; This is an excerpt of the file nodemon is being told to start (main entry point of the application in a file called /bin/www
, this was the default when I created the express application); as you can see I tried a bunch of things:
var app = require("../app");
var debug = require("debug")("server:server");
var http = require("http");
// terminus was built to handle this, right?
const { createTerminus } = require("@godaddy/terminus");
app.set("port", "3001");
/**
* Create HTTP server.
*/
var server = http.createServer(app);
// the terminus handler for SIGUSR2
function onSignal() {
console.log("server is starting cleanup");
// start cleanup of resource, like databases or file descriptors
}
async function onHealthCheck() {
// checks if the system is healthy, like the db connection is live
// resolves, if health, rejects if not
return true;
}
createTerminus(server, {
signal: "SIGUSR2",
healthChecks: { "/healthcheck": onHealthCheck },
onSignal
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
server.on("close", () => {
// this is never called on nodemon restart, it is when ctrl+c is pressed
console.log("Server close");
});
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
debug("Listening on " + bind);
}
process.on("SIGTERM", function() {
// this is never called
console.log("SIGTERM");
server.close(function() {
process.exit(0);
});
});
process.on("SIGINT", function() {
// this is only called on ctrl+c, not restart
console.log("SIGINT");
server.close(function() {
process.exit(0);
});
});
process.on("SIGUSR2", function() {
// never called
console.log("SIGUSR2");
server.close(function() {
process.exit(0);
});
});
process.on("beforeExit", () => {
// nope, never called
console.log("before exit");
});
process.on("exit", () => {
// only called on ctrl+c, not on restart
console.log("exit");
});
I am pretty sure at least one of those functions should handle the event and allow me to close the DB but if I start the server via nodemon /bin/www
I just get the output related to the startup, if I then restart the server by typing rs
, the output log looks like this:
Started directory watcher //normal startup
rs
[nodemon] starting `node ./bin/www` //none of the functions above is called