Suhas
Suhas

Reputation: 8458

How to stop nodemon from changing port on each restart of express app?

I am new to nodejs and this is first time I am using nodemon. I am using nodejs on windows. I have got following in my package.json file

"scripts": {
  "start": "nodemon ./bin/www"
}

And I use npm start from command line to start my express app. The process start with a default port which is annoying. But what is even more annoying is that every time I change a file nodemon restarts the application, sometimes on an entirely different random port number. I tried changing the script section in package.json file to the below but that did not make any difference

"scripts": {
  "start": "nodemon ./bin/www 3000"
},

Upvotes: 4

Views: 3881

Answers (1)

user2504723
user2504723

Reputation:

From the comments it seems you're specifying the port through an env variable, let's call it EXPRESS_PORT. The node process doesn't inherit it when you start it with npm because npm start creates a new shell with its own environment. So you end up passing port undefined to express. That makes it bind to a random free port. To fix this you can set the variable in the start command:

"scripts": {
    "start": "EXPRESS_PORT=3000 nodemon ./bin/www"
}

Or you can export it from your shell with export EXPRESS_PORT=3000 and then run npm start. If you do this you need to make sure to always export before starting the server, so you might want to place the export in ~/.profile or ~/.bashrc.

Upvotes: 1

Related Questions