149

I'd like to change the value of process.env.PORT, how can I do this?

I'm running Ubuntu 12.04.

Jay Prall
  • 5,295
  • 5
  • 49
  • 79
Dennis
  • 56,821
  • 26
  • 143
  • 139

5 Answers5

308

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
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 4
    For documentation sake, http://msdn.microsoft.com/en-us/library/windows/desktop/bb776899(v=vs.85).aspx for windows users – WraithKenny Sep 24 '13 at 02:42
  • 3
    Also for Powershell, it's `$env:PORT = 80` http://technet.microsoft.com/en-us/library/ff730964.aspx – WraithKenny Sep 24 '13 at 02:50
  • `VAR_1=value VAR_2=11827 node` -> simply use a space to use more than one variable on the same command – p4bloch Nov 18 '15 at 21:59
18

You can use cross platform solution https://www.npmjs.com/package/cross-env

$ cross-env PORT=1234
v2p
  • 649
  • 2
  • 10
  • 19
  • 1
    This is probably the best solution. There's way too much margin for error with the different terminals. I spent like 40 minutes until I found `cross-env` abstracts this problem away and just works. – adi518 Jun 16 '18 at 11:41
8

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 
Vikash Kumar
  • 399
  • 3
  • 4
2

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),

  1. Open up your bash profile vim ~/.bash_profile
  2. Add the environment variable to the file export PORT=80
  3. Open up the sudoers config file sudo visudo
  4. Add the following line to the file exactly as so Defaults env_keep +="PORT"

Now when you run sudo node app.js it should work as desired.

Community
  • 1
  • 1
Kyle Chadha
  • 3,741
  • 2
  • 33
  • 42
  • Running your node scripts as root (sudo) is not recommended. Use `sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080`, and listen on port 8080 instead. http://stigok.tumblr.com/post/139320914543/nodejs-http-listen-port-80-without-sudo-using – sshow Mar 06 '16 at 22:23
  • 1
    Yes, you're right, I've linked to a better discussion (that I also answered, *disclaimer*) and learned after initially using this approach. – Kyle Chadha Mar 06 '16 at 22:59
0

The easiest way would be:

PORT=2222 node-dev app.js
  • 2
    Please add further details to expand on your answer, such as working code or documentation citations. – Community Aug 27 '21 at 09:09