Home > OS >  Why can't I perform conditionals on environment variables in a node.js application
Why can't I perform conditionals on environment variables in a node.js application

Time:03-03

When I execute this node.js application...

if(process.env.ENV_ARG === "someValue") {
    console.log("conditional works...");
} else {
    console.log(`ENV_ARG => ${process.env.ENV_ARG}`);
}

with the following script...

  "scripts": {
    "dev": "SET ENV_ARG=someValue && node index.js"
  },

the output is:

ENV_ARG => someValue 

I can't understand why the if statement evaluates to false.
When the contents of process.env.ENV_ARG are logged in the else-block, they should be accessible for the if statement above...at least I thought so...

Thanks in advance

CodePudding user response:

It's a matter of spacing. There is a space that gets included at the end of the environment variable.

One way to work around it is the following:

  "scripts": {
    "dev": "SET ENV_ARG=someValue&& node index.js"
  },
  • Related