Seth Lutske
Seth Lutske

Reputation: 10686

Express server not exiting process and re-freeing port

I have an express server in a node app. I need to be able to run this node app with the debugger. I also need to be able to stop and restart the server easily without binding up the port it runs on. I need to tap into the shutdown to do some cleanup, which I do like this:

const server = app.listen(port, () => {
    console.log("Listening on port whatever");
});

process.on('SIGINT', function () {
    server.close(() => {
        console.log(chalk.blue('Shutting down server'));
        // some cleanup code
        process.exit();
    });
});

My start script uses nodemon to restart on save. Here are the relevant parts of my package.json related to that:

{
    "scripts": {
        "start:debug": "node --inspect -r tsconfig-paths/register -r ts-node/register ./src/server.ts",
        "start": "nodemon",
    },
    "nodemonConfig": {
        "ignore": [...],
        "watch": ["src"],
        "exec": "npm run start:debug",
        "ext": "ts"
    },
    "configurations": [
        {
            "type": "node",
            "request": "attach",
            "name": "Node: Nodemon",
            "processId": "${command:PickProcess}",
            "restart": true,
            "protocol": "inspector"
        }
    ]
}

This seems to work. It starts properly, is accessible through the node debugger, and restarts on save using nodemon. When I hit ctrl + c, the server shuts down and logs "Shutting down server". However, even after that get's logged, node logs Waiting for the debugger to disconnect.... When I hit ctrl + c again and rerun npm start, I get a crash saying Error: listen EADDRINUSE: address already in use :::PORT#.

What's going wrong here? My server seems to be shutting down gracefully, but the debugger seems to not shut down successfully, and there's a node process still hogging that port. Its getting difficult to start and stop my server cleanly and debug issues.

Upvotes: 1

Views: 669

Answers (1)

jfriend00
jfriend00

Reputation: 707376

To get the debugger to disconnect, you need to close the Chrome tab that has the debugger connection in it. That will allow the previous instance of your app to fully exit.

Upvotes: 1

Related Questions