简体   繁体   English

process.env.NODE_ENV 无论如何都不匹配“开发”

[英]process.env.NODE_ENV not matching 'development' no matter what

Just migrated on the latest Express, and stuck in something completely simple.刚刚迁移到最新的 Express,并陷入了完全简单的事情。 So, how is it possible, that this distilled example:那么,这个提炼的例子怎么可能:

var env = process.env.NODE_ENV || 'development';
console.log(env);
if ('development' == env) {
    console.log('im here');    
}
else {
    console.log('nah');    
    console.log(env);
}

with this server file runned as SET NODE_ENV=development & node server.js将此服务器文件作为 SET NODE_ENV=development & node server.js 运行

gives output:给出输出:

development
nah
development

instead of代替

development
im here

By the way, if I'll just manually set var env = 'development' then it work as it should be.顺便说一下,如果我只是手动设置var env = 'development'那么它应该可以正常工作。

express 4.11.2, node 0.12.0, win8 x64. express 4.11.2,节点 0.12.0,win8 x64。

I got same problem on windows mode.我在 Windows 模式下遇到了同样的问题。 I'm not sure on linux.我不确定在 linux 上。 This problem caused by spaces between word "development" with "&" character.这个问题是由单词“development”与“&”字符之间的空格引起的。 You can fix by remove spaces on your command.您可以通过删除命令中的空格来修复。 Example: SET NODE_ENV=development& node server.js示例: SET NODE_ENV=development& node server.js

Your code looks fine, therefore the reason the equality test must be failing is because the strings aren't equal.您的代码看起来不错,因此相等测试必须失败的原因是因为字符串不相等。 Make sure you don't have any extra characters like spaces in your environment variable development string.确保您的环境变量开发字符串中没有任何额外的字符,如空格。

同样的问题,我发现使用env.includes('development')代替没问题。

I tried going with the recommendations here but nothing managed to rid me of the wayward space.我试着按照这里的建议去做,但没有什么能让我摆脱任性的空间。

so I just trim the variable where it needs to be used:所以我只是在需要使用它的地方修剪变量:

require('dotenv').config();

const configSet = () => {
  const envData = process.env;

  console.log('configSet -> process.env', envData);
  console.log('configSet -> envData.NODE_ENV', envData.NODE_ENV);
  const prodOrDevMode = envData.NODE_ENV.trim();

  switch (prodOrDevMode) {
    case 'development':
      envData.TABLE_NAME = envData.DB_TABLE_DEV;
      return envData;

    case 'production':
      envData.TABLE_NAME = envData.DB_TABLE_PROD;
      return envData;

    default:
      throw new Error('Incorrect env setting');
  }
};

const config = configSet();

module.exports = { config };

I'd appreciate any feedback on this in particular if this may cause issues如果这可能会导致问题,我将不胜感激

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM