Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use node.js commandline argument as environment variable

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
like image 737
CPI Avatar asked Jul 31 '26 22:07

CPI


2 Answers

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.

like image 93
Jordan Breton Avatar answered Aug 02 '26 13:08

Jordan Breton


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/

like image 30
Eftakhar Avatar answered Aug 02 '26 11:08

Eftakhar