4

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
CPI
  • 43
  • 1
  • 5

3 Answers3

4

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.

Jordan Breton
  • 1,167
  • 10
  • 17
  • Thank you! That works. BTW: I'm on Windows. So the environment variable can be used with `$env:a="5"` in a previous command (not in the same line). – CPI Apr 05 '22 at 07:43
1

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/

Eftakhar
  • 455
  • 4
  • 17
1

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.

Arnav Thorat
  • 3,078
  • 3
  • 8
  • 33