如何检查Node.js中是否设置了环境变量?

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)

  • 由于这似乎多年来一直在上升,我只是想指出,如果环境变量的值是一个假值,它可能不会产生预期的结果. (13认同)

max*_*kov 9

我使用这个片段来找出是否设置了环境变量

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将隐式地将值转换为字符串。

 process.env.test = null
 console.log(process.env.test);
 // => 'null'
 process.env.test = undefined;
 console.log(process.env.test);
 // => 'undefined'
Run Code Online (Sandbox Code Playgroud)

不过,当变量没有在环境中设置,相应的键不存在process.env所有对象和的相应的属性process.envundefined

这是另一个示例(请注意示例中使用的引号):

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 移开了:它在这里

  • 我只是想给这个答案投赞成票,但结果发现这是我的。人生就是这么荒唐…… (3认同)

Kos*_*nos 5

我练习使用内置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)