Sunday, August 21, 2022

[FIXED] Why can't I perform conditionals on environment variables in a node.js application

Issue

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


Solution

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"
  },


Answered By - Ben
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.