How to change value of process.env.PORT in node.js?

node.jsEnvironment Variables

node.js Problem Overview


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

I'm running Ubuntu 12.04.

node.js Solutions


Solution 1 - node.js

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

Solution 2 - node.js

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

$ cross-env PORT=1234

Solution 3 - node.js

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 

Solution 4 - node.js

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: https://stackoverflow.com/questions/6109089/how-do-i-run-node-js-on-port-80/27805105#27805105

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.

Solution 5 - node.js

The easiest way would be:

PORT=2222 node-dev app.js

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDennisView Question on Stackoverflow
Solution 1 - node.jsJohnnyHKView Answer on Stackoverflow
Solution 2 - node.jsv2pView Answer on Stackoverflow
Solution 3 - node.jsVikash KumarView Answer on Stackoverflow
Solution 4 - node.jsKyle ChadhaView Answer on Stackoverflow
Solution 5 - node.jsLeo ZengView Answer on Stackoverflow