Search code examples
expressslack-apinodemon

EADDRINUSE error: How do you run nodemon with express so it does not listen to a port that is already in use?


I am working on a slack bot tutorial that runs express server and runs concurrently, nodemon, and ngrok.

The problem I am running into is:

Error: listen EADDRINUSE: address already in use :::5000

I think the error happens because nodemon re-runs express when an update happens. index.js:

const server = app.listen(process.env.PORT || 5000, () => {
  console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env);
});

I've gone down several rabbit holes that include parent and child 'processes' (https://dev.to/kyrelldixon/how-to-setup-an-express-js-server-in-node-js-56hp)

And / or it looks like this may be some kind of bug due to an update (https://github.com/remy/nodemon/issues/1025)

I have even thought about adding some kind of callback on .listen so app checks for whether or not a port is running (http://expressjs.com/en/5x/api.html#app.listen_path_callback)

But ultimately, not sure how to figure out the issue. Can anyone provide some guidance?

my setup:

npm -v
1.5.0
node -v
v10.16.3
nodemon -v
v2.0.2
express -v
v4.16.0

Solution

  • adding something like

    process.on(‘SIGINT’, () => { console.log(“exiting…“); process.exit(); });
    
    process.on(‘exit’, () => { console.log(“exiting…“); process.exit(); });
    

    in your main js file should catch these situations and allow for you to make sure the process exits properly. You could expand to call a function to additional clean up as well