question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Ctrl + C ends up with continual EADDRINUSE errors after nodemon tries to restart expressJS

See original GitHub issue

I do not know if this is a bug but suspect it is?

I’m using node v14.4.0 so latest. nodemon ^2.0.4

Don’t know what the behavior should be but I figured if I Ctrl + C, nodemon and my expressJS server should stop and no longer hog whatever port expressJS is running on

Error: bind EADDRINUSE null:3000
    at listenOnMasterHandle (net.js:1380:18)
    at rr (internal/cluster/child.js:132:12)
    at Worker.<anonymous> (internal/cluster/child.js:99:7)
    at process.onInternalMessage (internal/cluster/utils.js:47:8)
    at process.emit (events.js:327:22)
    at emit (internal/child_process.js:906:12)
    at processTicksAndRejections (internal/process/task_queues.js:85:21)
Emitted 'error' event on Server instance at:
    at listenOnMasterHandle (net.js:1381:21)
    at rr (internal/cluster/child.js:132:12)
    [... lines matching original stack trace ...]
    at processTicksAndRejections (internal/process/task_queues.js:85:21) {
  errno: -48,
  code: 'EADDRINUSE',
  syscall: 'bind',
  address: null,
  port: 3000
}

The only way I can manually kill it and temporarily move on is to use pkill node. lsof -i :3000 -t | xargs kill` doesn’t work.

This happens after I Ctrl + C and then try to run yarn dev again

My Scripts:

"start": "PORT=3000 nodemon --trace-warnings dist/server/server.js",
"build": "NODE_ENV=production webpack -p --env=prod --watch && yarn compile-server && yarn start",
"dev": "NODE_ENV=development yarn lint && yarn copyData && yarn compile-server && yarn start & webpack-dev-server",
"compile-server": "tsc -b ./src/server",
"copyData": "mkdir -p dist/shared/data && cp src/shared/data/companies.json dist/shared/data && cp src/shared/data/countries.json dist/shared/data",

here it is running the first time I fire it up after say I reboot my machine and there are no processes running yet: Screen Shot 2020-08-05 at 12 58 50 PM

If I then Ctrl + C then run yarn dev OR if nodemon or something errors and nodemone trys to restart itself, I get:

Screen Shot 2020-08-05 at 12 55 38 PM

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:12 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
BibekSthacommented, Aug 26, 2020

That helps. Thanks a lot @jylauril!! I was looking for a solution to this problem for a long time. I now have the solution and also understand a little more about nodemon and nodejs.

@remy As you were going to, it would be great to add the code in FAQ, as many people are facing this issue. Here is the modified code as per @jylauril, for your reference.

    // app.listen returns a NodeJS http.Server instance
    const httpServer = app.listen(port, host);

    // clean exit the server and node process when one of these events occur
    [`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`].forEach((event) => {
      process.on(event, () => {
        httpServer.close(() => process.exit())
      })
    })

Please modify the code block with your expertise, thanks.

1reaction
jylaurilcommented, Aug 26, 2020

@BibekStha Yeah, just one thing: the httpServer.close is actually asynchronous so you shouldn’t call process.exit immediately after it. Otherwise you’re bound to have the exact same problem of exiting the process before the connection is closed 😄

Technically if all your connections and servers are closed, your process should exit on its own, but sometimes it can be a bit cumbersome to manage everything. In this case the original problem was the web server not being able to re-bind itself after the restart so if the process doesn’t exit on its own and you don’t want to deal with other connections then it should be fine to process.exit.

Just edit the code to do this instead:

httpServer.close(() => process.exit())

In my node projects I usually make a little class called ServerState that extends from EventEmitter and it has a shutdown method that just emits shutdown event on itself. The constructor to that class just binds the signal listeners that then calls the shutdown method on itself. Then every time I register a new server or connection, I just do: in my express code:

const httpServer = app.listen(port);
serverState.once('shutdown', () => httpServer.close())

in my mongoose initialization code:

await mongoose.connect(options);
serverState.once('shutdown', () => mongoose.connection.close())

This way once all the connections are closed, the process exits on its own and I don’t have to worry about anything leaving hanging.

Read more comments on GitHub >

github_iconTop Results From Across the Web

expressJS and nodemon on Ctrl + C and restart: Error: bind ...
Once my express server is up and running, if I Ctrl + C on it then try to run yarn dev again I...
Read more >
Bind Eaddrinuse Null:3000 When Stopping And Restarting
Ctrl + C ends up with continual EADDRINUSE errors after nodemon tries to restart expressJS #1748 Error: bind EADDRINUSE null:3000 at listenOnMasterHandle ...
Read more >
How To Set Up An Express API Backend Project With ...
Stop your server (use Ctrl + C ) and run yarn start . You'll get an error SyntaxError: Invalid or unexpected token ....
Read more >
How to Build a Secure Server with Node.js and Express and ...
In this tutorial, we will learn how to create a server. ... Use Control/Command + C to terminate the server and run node...
Read more >
Let It Crash: Best Practices for Handling Node.js Errors on ...
Some strategies to gracefully shutdown the Node.js process and quickly restart your application after a catastrophic error terminates your ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found