env. PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there's nothing there. So you pass that to app. listen , or to app. set('port', ...) , and that makes your server able to accept a "what port to listen on" parameter from the environment.
When trying to access process. env. PORT it'll return undefined if you've not setup that environment variable in the shell that you're trying to run your system. You can set the environment variable up before you run node app.
For just one run (from the unix shell prompt):
$ PORT=1234 node app.js
More permanently:
$ export PORT=1234
$ node app.js
In Windows:
set PORT=1234
In Windows PowerShell:
$env:PORT = 1234
You can use cross platform solution https://www.npmjs.com/package/cross-env
$ cross-env PORT=1234
use the below command to set the port number in node process while running node JS programme:
set PORT =3000 && node file_name.js
The set port can be accessed in the code as
process.env.PORT
EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?
Original Answer:
If you want to do this to run on port 80 (or want to set the env variable more permanently),
vim ~/.bash_profile
export PORT=80
sudo visudo
Defaults env_keep +="PORT"
Now when you run sudo node app.js
it should work as desired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With