简体   繁体   English

在node.js中从不同文件设置环境变量?

[英]Setting Environment Variables from different files in node.js?

I have two different Environment development and production 我有两种不同的环境开发和生产

production.js production.js

var config = {   
  production: {  
    session: {    
      key: 'the.express.session.id',    
      secret: 'something.super.secret'    
    },    
    database: 'mongodb://localhost:27018/test',    
    twitter: {    
      consumerKey: 'consumer Key',    
      consumerSecret: 'consumer Secret',    
      callbackURL: 'http://yoururl.com/auth/twitter/callback'    
    }    
  },    
}

development.js development.js

var config = {    
  development: {    
    session: {    
      key: 'the.express.session.id',    
      secret: 'something.super.secret'    
    },    
    database: 'mongodb://localhost:27018/testdata',    
    twitter: {    
      consumerKey: 'consumer Key',    
      consumerSecret: 'consumer Secret',    
      callbackURL: 'http://yoururl.com/auth/twitter/callback'    
    }    
  },    
}

I have stored these files under environment folder now i want to call these two files in server.js 我已将这些文件存储在环境文件夹下,现在我想在server.js中调用这两个文件

server.js server.js

var config = require('./environment');    
console.log(config);    

mongoose.connect(config.database);    
mongoose.connection.on('error', function (err) {    
  console.error('MongoDB connection error: ' + err);    
  process.exit(-1);    
});

How can i call those file in server.js .if i run set NODE_ENV=production in command prompt these should run production database and if i run set NODE_ENV=development in command prompt development database should run .help me out 我如何在server.js中调用这些文件。如果我在命令提示符下运行set NODE_ENV=production ,这些应该运行production数据库,如果我在命令提示符下运行set NODE_ENV=development ,则development数据库应该运行.help me

When require is given the path of a folder, it'll look for an index.js file in that folder; 当给了require文件夹路径后,它将在该文件夹中寻找一个index.js文件。 if there is one, it uses that, and if there isn't, it fails. 如果有,则使用它,如果没有,则失败。

It would probably make most sense (if you have control over the folder) to create an index.js file and then test process.env : 如果您可以控制文件夹,那么创建一个index.js文件然后测试process.env可能是最有意义的:

if (process.env.NODE_ENV === 'production') {
  require('production.js');
} else {
  require('development.js');
}

node.js require all files in a folder? node.js是否需要文件夹中的所有文件?

https://www.twilio.com/blog/2017/08/working-with-environment-variables-in-node-js.html https://www.twilio.com/blog/2017/08/working-with-environment-variables-in-node-js.html

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

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