简体   繁体   中英

process.env.NODE_ENV not matching 'development' no matter what

Just migrated on the latest Express, and stuck in something completely simple. 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

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.

express 4.11.2, node 0.12.0, win8 x64.

I got same problem on windows mode. I'm not sure on linux. This problem caused by spaces between word "development" with "&" character. You can fix by remove spaces on your command. Example: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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