I am trying to create some setup and teardown logic for an expressjs server. Here's my entry code:
import fs from "fs";
import express from "express";
import { setRoutes } from "./routes";
let app = express();
const server = app.listen(8080, function () {
console.log(` Mock Server is now running on port : ${8080}`);
});
app = setRoutes(app);
function stop() {
fs.rmdirSync("./uploads", { recursive: true });
fs.mkdirSync("uploads");
console.log("\n Uploads folder purged");
server.on("close", function () {
console.log("⬇ Shutting down server");
process.exit();
});
server.close();
}
process.on("SIGINT", stop);
// Purge sw images on restart
process.once("SIGUSR2", function () {
fs.rmdirSync("./uploads/swimages", { recursive: true });
console.log(" Software Images folder purged");
process.kill(process.pid, "SIGUSR2");
});
The npm script to start this up is "start": "FORCE_COLOR=3 nodemon index.js --exec babel-node"
.
The setup and restart logic works as expected. I get Mock Server is now running on port : 8080
logged to console on startup. When I save a file, nodemon restarts the server, and the code in process.once
is executed. When I want to shut it all down, I ctrl + c
in the terminal. The cleanup logic from within the stop
function is run. However, the process bever fully exits. In the terminal, am still stuck in the process, and I have to hit ctrl + c
again to fully exit the process. It looks like this:
As far as I know there are no open connections (other questions mentioned that if there is a keep-alive
connection still open, the server will not close properly, but as far as I can tell, that is not the case). I have tried different variations of server.close(callback)
, server.on('close', callback)
, process.exit()
, process.kill(process.pid)
, etc, but nothing seems to fully exit the process.
Note that if I simply run node index.js
, I do not have this issue. The cleanup logic runs, and the process exits to completion without issue. It seems to be an issue when using nodemon only.
I don't want other developers to have to wait for cleanup logic to run and then hit ctrl + c again. What am I missing to run my cleanup logic and fully exit the process in the terminal?