0

I am not very experienced in Nodejs but I am trying to fetch some some information in my node app that I will pass from CMD/terminal that I will access through process.env in my app.

For example, I want to pass PORT NUMBER through env in my node and fetching the same using below line:

const PORT = process.env.PORT || 3001  

and I am passing port number at the time of running node app using below command line:

node server.js PORT=4200  

The above one is not working. After searching on google, many people giving solution to achieve the same by running below command line:

PORT=4200 node server.js  

By running above command, I am getting error in command line as given below:

'PORT' is not recognized as an internal or external command, operable program or batch file.  

Can someone please let me know, how can I pass variable at the time of running node app and access the same in node app. I don't want to use any env file. I just only want to pass info from command line.

Thanks in advance

Dhirender
  • 604
  • 8
  • 23
  • Does this answer your question? [How do I pass command line arguments to a Node.js program?](https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program) – Sivasankaran K B Mar 01 '22 at 06:04
  • Powershell or command prompt? See [Setting and using variable within same command line in Windows cmd.exe](https://superuser.com/q/223104/81031) – Phil Mar 01 '22 at 06:12

1 Answers1

0

Command-line arguments are traditionally passed in via the process.argv array. argv[0] contains the process name node, argv[1] contains the first command line argument, etc... So, you can run:

node server.js 4200

and from node, do:

const port = parseInt(process.argv[1], 10);

See How do I pass command line arguments to a Node.js program?

If you must use environment variables, Node's process.env contains the environment variables of the node process. The set command is used to store a value in an environment var on Windows. Then run node:

set PORT=4200
node server.js

More examples of the set command can be found here: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/set_1#examples .

Sivasankaran K B
  • 322
  • 3
  • 10