Home > Enterprise >  Use node.js commandline argument as environment variable
Use node.js commandline argument as environment variable

Time:04-05

I call my node.js application with

node index.js a=5

I want to use the value '5' directly as an environment variable in my code like

const myNumber = process.env.a

(like stated here).

If I try the above, 'MyNumber' is undefinded on runtime.

Solution

  • Linux:
a=5 node index.js
  • Windows (Powershell):
    $env:a="5";node index.js

CodePudding user response:

When doing node index.js a=5, a=5 is an argument for node, as index.js is.

If you want to pass an environment variable, you must specify it before node command : a=5 node index.js.

The node process.env is populated with your bash environment variables.

CodePudding user response:

a=5 is an argument to your script not an environment variable. to access the argument in the script use process.argv

https://nodejs.org/en/knowledge/command-line/how-to-parse-command-line-arguments/

CodePudding user response:

Right now, when you run the following command, it is setting an argument for Node.js (your index.js file).

$ node index.js a=5

You can access this using the code below. It will simply return the value the first value passed in.

// node index.js a=5
process.argv[2]

You need to get the 2nd index, as the first 2 are just command line ones.


If you want to pass an environment variable, you need to set it before running the command, as so.

$ a=5 node index.js

You can then access it with process.env, as you have already specified.

  • Related