use*_*780 19 javascript environment-variables node.js
我想检查我的Node.js Express服务器中是否设置了环境变量,并根据是否设置了不同的操作.
我试过这个:
if(process.env.MYKEY !== 'undefined'){
console.log('It is set!');
} else {
console.log('No set!');
}
Run Code Online (Sandbox Code Playgroud)
我正在测试没有,process.env.MYKEY但控制台打印"它已设置".
kuc*_*ang 25
这在我的Node.js项目中工作正常:
if(process.env.MYKEY) {
console.log('It is set!');
}
else {
console.log('No set!');
}
Run Code Online (Sandbox Code Playgroud)
我使用这个片段来找出是否设置了环境变量
if ('DEBUG' in process.env) {
console.log("Env var is set:", process.env.DEBUG)
} else {
console.log("Env var IS NOT SET")
}
Run Code Online (Sandbox Code Playgroud)
正如NodeJS 8 文档中提到的:
该
process.env属性返回一个包含用户环境的对象。参见环境(7)。[...]
分配一个属性
process.env将隐式地将值转换为字符串。Run Code Online (Sandbox Code Playgroud)process.env.test = null console.log(process.env.test); // => 'null' process.env.test = undefined; console.log(process.env.test); // => 'undefined'
不过,当变量没有在环境中设置,相应的键不存在在process.env所有对象和的相应的属性process.env是undefined。
这是另一个示例(请注意示例中使用的引号):
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'
Run Code Online (Sandbox Code Playgroud)
我把答案中这个尴尬而奇怪的部分从 StackOverflow 移开了:它在这里
我练习使用内置Node.js 断言库。
const assert = require('assert');
assert(process.env.MY_VARIABLE, 'MY_VARIABLE is missing');
// or if you need to check some value
assert(process.env.MY_VARIABLE.length > 1, 'MY_VARIABLE should have length greater then 1');
Run Code Online (Sandbox Code Playgroud)
我通常在index.js之上添加此验证,并使其符合代码要求。如果由于某种原因 .env.example 不在代码中,这种方法也可以轻松检查项目需要哪些变量。
这也是我使用的更新版本,很容易维护,并在那里添加/删除变量检查:
const assert = require('assert');
assert(process.env.MY_VARIABLE, 'MY_VARIABLE is missing');
// or if you need to check some value
assert(process.env.MY_VARIABLE.length > 1, 'MY_VARIABLE should have length greater then 1');
Run Code Online (Sandbox Code Playgroud)