1

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:

enter image description here

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?

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78

1 Answers1

0

There is an open connection for sure. Check this package that can tell you which one: https://www.npmjs.com/package/wtfnode

mmomtchev
  • 2,497
  • 1
  • 8
  • 23
  • So that's a very interesting package, that told me that my use of [WatchJS](https://github.com/melanke/Watch.JS/) is an open connection when trying to shut down the server. But I'm having a hard time believing that's my real issue. If I simply do `node index.js` from the terminal, a `ctrl + c` properly shuts everything down as expected. But with nodemon, I get the issue described. Why would that happen with nodemon? – Seth Lutske Jan 10 '22 at 18:35