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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.