Javascript 如何检查 Node.js 中是否设置了环境变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/30047205/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if an environment variable is set in Node.js?
提问by user3812780
I would like to check if an environment variable is set in my Express JSserver and perform different operations depending on whether or not it is set.
我想检查我的Express JS服务器中是否设置了环境变量,并根据是否设置执行不同的操作。
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.MYKEYbut the console prints "It is set".
我正在测试,process.env.MYKEY但控制台打印“已设置”。
回答by kucing_terbang
This is working fine in my Node.js project:
这在我的 Node.js 项目中运行良好:
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 falsein snippet above. In case a falsy value is considered as valid value. Use hasOwnPropertyor checking the value once again inside the block.
请注意,正如@Salketer 所提到的,根据需要,假值将被视为false上面的代码片段。如果将假值视为有效值。hasOwnProperty在块内再次使用或检查该值。
> x = {a: ''}
{ a: '' }
> x.hasOwnProperty('a')
true
Or, feel free to use the in operator
或者,随意使用 in 运算符
if ("MYKEY" in process.env) {
    console.log('It is set!');
} else {
    console.log('No set!');
}
回答by maxkoryukov
I use this snippet to find out whether the environment variable is set
我使用这个片段来找出是否设置了环境变量
if ('DEBUG' in process.env) {
  console.log("Env var is set:", process.env.DEBUG)
} else {
  console.log("Env var IS NOT SET")
}
Theoretical Notes
理论笔记
As mentioned in the NodeJS 8 docs:
正如NodeJS 8 文档中提到的:
The
process.envproperty returns an object containing the user environment. See environ(7).[...]
Assigning a property on
process.envwill implicitly convert the value to a string.process.env.test = null console.log(process.env.test); // => 'null' process.env.test = undefined; console.log(process.env.test); // => 'undefined'
该
process.env属性返回一个包含用户环境的对象。参见环境(7)。[...]
分配一个属性
process.env将隐式地将值转换为字符串。process.env.test = null console.log(process.env.test); // => 'null' process.env.test = undefined; console.log(process.env.test); // => 'undefined'
Though, when the variable isn't set in the environment, the appropriate key is not presentin the process.envobject at all and the corresponding property of the process.envis undefined.
不过,当变量没有在环境中设置,相应的键不存在在process.env所有对象和的相应的属性process.env是undefined。
Here is another one example (be aware of quotes used in the example):
这是另一个示例(请注意示例中使用的引号):
console.log(process.env.asdf, typeof process.env.asdf)
// => undefined 'undefined'
console.log('asdf' in process.env)
// => false
// after touching (getting the value) the undefined var 
// is still not present:
console.log(process.env.asdf)
// => undefined
// let's set the value of the env-variable
process.env.asdf = undefined
console.log(process.env.asdf)
// => 'undefined'
process.env.asdf = 123
console.log(process.env.asdf)
// => '123'
A side-note about the code style
关于代码风格的旁注
I moved this awkward and weird part of the answer away from StackOverflow: it is here
我把答案中这个尴尬而奇怪的部分从 StackOverflow 移开了:它在这里
回答by MikeCPT
Why not check whether the key exists in the environment variables?
为什么不检查环境变量中是否存在密钥?
if ('MYKEY' in Object.keys(process.env))
    console.log("It is set!");
else
    console.log("Not set!");
回答by Display name
EDIT(removed old incorrect answer)
编辑(删除旧的错误答案)
As maxkoryukovsaid, it should be:
正如maxkoryukov所说,应该是:
# in test.js
if ("TEST_ENV" in process.env) {
    console.log("TRUE: " + process.env["TEST_ENV"])
} else {
    console.log("FALSE")
}
This was true with he following test:
他下面的测试确实如此:
$> node test.js
FALSE
$> export TEST_ENV="SOMETHING"
$> node test.js
TRUE: SOMETHING
This also works when the variable is an empty string (tested in a new bash session/terminal window).
当变量为空字符串(在新的 bash 会话/终端窗口中测试)时,这也适用。
$> node test.js
FALSE
$> export TEST_ENV=""
$> node test.js
TRUE:
回答by Jee Mok
As the value (if exist) will be a string, as mentioned in the documentation:
由于值(如果存在)将是一个字符串,如文档中所述:
process.env.test = null;
console.log(process.env.test);
// => 'null'
process.env.test = undefined;
console.log(process.env.test);
// => 'undefined'
and empty string can be returned (that happened to me in CI process + GCP server),
并且可以返回空字符串(在 CI 进程 + GCP 服务器中发生在我身上),
I would create a function to clean the values from process.env:
我会创建一个函数来清除以下值process.env:
function clean(value) {
  const FALSY_VALUES = ['', 'null', 'false', 'undefined'];
  if (!value || FALSY_VALUES.includes(value)) {
    return undefined;
  }
  return value;
}
const env = {
  isProduction: proces.env.NODE_ENV === 'production',
  isTest: proces.env.NODE_ENV === 'test',
  isDev: proces.env.NODE_ENV === 'development',
  MYKEY: clean(process.env.MYKEY),
};
// Read an environment variable, which is validated and cleaned
env.MYKEY           // -> 'custom values'
// Some shortcuts (boolean) properties for checking its value:
env.isProduction    // true if NODE_ENV === 'production'
env.isTest          // true if NODE_ENV === 'test'
env.isDev           // true if NODE_ENV === 'development'
回答by Evan Parsons
If you're assigning a value with your if statement, you could do it like this
如果你用 if 语句赋值,你可以这样做
var thisIsSet = 'asddas';
var newVariable = thisIsSet ||'otherValue'
console.log(newVariable)
Results in asddas
结果在 asddas
回答by Max Chou
It's good way to check your environment variable
这是检查环境变量的好方法
if (process.env.YOUR_ VARIABLE) {
    // If your variable is exist
}
Otherwise, If you would like to check multiple environment variables, you can check this node moduleout.
否则,如果你想检查多个环境变量,你可以检查node module一下。
回答by Amit Nambiar
let dotenv;
try {
  dotenv = require('dotenv');
  dotenv.config();
}
catch(err) {
  console.log(err);
  // if vars are not available...
}
//... vars should be available at this point

