2

I have two different Environment development and production

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

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

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

1 Answers1

0

When require is given the path of a folder, it'll look for an index.js file in that folder; 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 :

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

node.js require all files in a folder?

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

Patrice Rolland
  • 49
  • 2
  • 11