Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
168
rated 0 times [  172] [ 4]  / answers: 1 / hits: 78894  / 9 Years ago, tue, may 5, 2015, 12:00:00

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.


More From » node.js

 Answers
8

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!');
}

[#66745] Sunday, May 3, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
everardo

Total Points: 406
Total Questions: 104
Total Answers: 92

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;