how to run node.js app from cmd with some predefined port in Windows

20,141

Solution 1

A simple adding to Alberto's answer. On Windows machine you haven't export command in cmd, use set instead. Then the whole script will be looks like this:

set PORT=7777
node server.js

Note that the syntax in PowerShell is slightly different:

$env:PORT=7777
node server.js

Solution 2

Depending on what server.js contains you should be able to do so.

At a minimum you should read port (you could use https://github.com/substack/node-optimist)

var argv = require('optimist').argv;
console.log(argv.port);

// use it like this
$ node server.js -port 7777

and then listen to it on your server (this depends on what lib you're using).

Run the server like this

export PORT=7777; node server.js

Solution 3

for linux export PORT=5000; node index.js

for windows set PORT=5000; node index.js

in case of powerShell

set $env:PORT=5000; node index.js

const port = process.env.PORT || 3000; app.listen(port,()=>{console.log(Listening on port ${port})})

Share:
20,141
silent_coder
Author by

silent_coder

Updated on July 12, 2022

Comments

  • silent_coder
    silent_coder almost 2 years

    Is it some command exist to run my node.js code with directly specified port? something like node server.js port=7777 ?

    my server.js code looks like this

    http.createServer(function (req, res) {
      if (mount(req, res)) return;
    }).listen(process.env.PORT || 80);
    
  • silent_coder
    silent_coder over 10 years
    I update the question with server.js code. Is it possible to do that without modifying server.js content?
  • Manjeet
    Manjeet almost 7 years
    @AlbertoZaccagni node server.js -port 8000 this one saved my day. Thanks a lot :)
  • tarekahf
    tarekahf over 3 years
    Thank you so much. I really love this approach. I did fiddle with the "optimistic" module at my end under Windows. There is an error in your example based on my setup. The command line should be node server.js --port 7777 and you should install the module using npm install optimistic. Now I am able to pass the port in the command line of the node.exe program. But, I could not figure out how to debug this part. In VS Code I can only debug all other parts except the part which is listening to the server. Any feedback?
  • Alberto Zaccagni
    Alberto Zaccagni over 3 years
    @tarekahf I suggest you to open a new question quoting this one as a reference