Search code examples
node.jsportexitsigintctl

Why pressing Ctrl + C to interrupt a node js server application doesn't close previous opened ports?


I have an express server on localhost:3000. The problem is whenever I restart the server I get: EADDRINUSE. So the server will run on port 3001. I have solved this problem by manually killing PID using port 3000 but I'm curious about why ports are't closed succesfully. Is it a bug?

I did a little research and I found how to detect ctl + c signal interruption and then exit. This lines of code solved my problem so when pressing ctl + c ports are closed.

`process.on('SIGINT', function() {
      console.log("EXIT");
      process.exit();
});

But I still would like to know why nodejs doesn't close then by default then interrupting.


Solution

  • If the server is not being shut down gracefully, it might not have a chance to release the port before the process is terminated.

    If there are asynchronous operations or background tasks running that are not properly handled before shutting down the server, it can result in the port not being released in time.

    In some cases, the operating system might take some time to release the resources associated with a terminated process.

    By adding a signal handler, such as the one for SIGINT in your example, you ensure that the server has a chance to close properly before the process exits. This allows the server to release the port and avoid the EADDRINUSE error when restarting.