PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 19, 2022

[FIXED] How can I check if an environment variable is set in Node.js?

 August 19, 2022     environment-variables, javascript, node.js     No comments   

Issue

I would like to check if an environment variable is set in my Express JS server and perform different operations depending on whether or not it is set.

I've tried this:

if(process.env.MYKEY !== 'undefined'){
    console.log('It is set!');
} else {
    console.log('No set!');
}

I'm testing without the process.env.MYKEY but the console prints "It is set".


Solution

This is working fine in my Node.js project:

if(process.env.MYKEY) { 
    console.log('It is set!'); 
}
else { 
    console.log('No set!'); 
}

EDIT:

Note that, As @Salketer mentioned, depends on the needs, falsy value will be considered as false in snippet above. In case a falsy value is considered as valid value. Use hasOwnProperty or checking the value once again inside the block.

> x = {a: ''}
{ a: '' }
> x.hasOwnProperty('a')
true

Or, feel free to use the in operator

if ("MYKEY" in process.env) {
    console.log('It is set!');
} else {
    console.log('No set!');
}


Answered By - kucing_terbang
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing