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

How can I check if an environment variable is set in Node.js?

我想检查我的 Express JS 服务器中是否设置了环境变量,并根据是否设置执行不同的操作。

我试过这个:

if(process.env.MYKEY !== 'undefined'){
    console.log('It is set!');
} else {
    console.log('No set!');
}

我在没有 process.env.MYKEY 的情况下进行测试,但控制台打印 "It is set"。

这在我的 Node.js 项目中运行良好:

if(process.env.MYKEY) { 
    console.log('It is set!'); 
}
else { 
    console.log('No set!'); 
}

编辑:

请注意,正如@Salketer 提到的,根据需要,虚假值将被视为上面代码段中的 false。如果一个虚假值被认为是有效值。使用 hasOwnProperty 或再次检查块内的值。

> x = {a: ''}
{ a: '' }
> x.hasOwnProperty('a')
true

或者,随意使用 in 运算符

if ("MYKEY" in process.env) {
    console.log('It is set!');
} else {
    console.log('No set!');
}
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

这是检查环境变量的好方法

if (process.env.YOUR_ VARIABLE) {
    // If your variable is exist
}

否则,如果你想检查多个环境变量,你可以检查这个node module

node-envchecker

为什么不检查环境变量中是否存在key?

if ('MYKEY' in Object.keys(process.env))
    console.log("It is set!");
else
    console.log("Not set!");

如果你用 if 语句赋值,你可以这样做

var thisIsSet = 'asddas';
var newVariable = thisIsSet ||'otherValue'
console.log(newVariable)

asddas 中的结果

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

if ('DEBUG' in process.env) {
  console.log("Env var is set:", process.env.DEBUG)
} else {
  console.log("Env var IS NOT SET")
}

理论笔记

NodeJS 8 docs所述:

The process.env property returns an object containing the user environment. See environ(7).

[...]

Assigning a property on process.env will 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 对象中根本不存在 和相应的 属性 的 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'

关于代码风格的旁注

我从 Whosebug 中移走了答案中这个尴尬和奇怪的部分:it is here

编辑(删除旧的错误答案)

maxkoryukov所说,应该是:

# in test.js

if ("TEST_ENV" in process.env) {
    console.log("TRUE: " + process.env["TEST_ENV"])
} else {
    console.log("FALSE")
}

他进行了以下测试:

$> node test.js
FALSE
$> export TEST_ENV="SOMETHING"
$> node test.js
TRUE: SOMETHING

这在变量为空字符串时也有效(在新的 bash session/terminal window 中测试)。

$> node test.js
FALSE
$> export TEST_ENV=""
$> node test.js
TRUE:

因为值(如果存在)将是一个字符串,如 documentation 中所述:

process.env.test = null;
console.log(process.env.test);
// => 'null'
process.env.test = undefined;
console.log(process.env.test);
// => 'undefined'

并且可以返回空字符串(在 CI 进程 + GCP 服务器中发生在我身上),

我会创建一个函数来清除 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'

您可以创建 .env.example 来存储应用程序所需的所有环境变量。
在此之后,您可以加载此 .env.example 并与 .env.

进行比较

通过这种方式,您可以在应用程序启动时检查所有需要的环境。

要最小化任务,您可以使用 scan-env npm 包,它的作用相同。

const scanEnv = require("scan-env");

const scanResult = scanEnv();

if (!scanResult) {
  console.error("Environment variables are missing.");
}

tutorial to use scan-env

你可以用||轻松解决具有默认值属性的运算符情况下环境变量不存在:

const mykey = process.env.MYKEY || '1234';

我练习使用内置 Node.js assert library

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

我过去常常在 index.js 之上添加此验证,并使其与代码要求保持同步。 如果由于某种原因 .env.example 不在代码中,这种方式也很容易检查项目需要哪些变量。