FastFoodCoding

Login


Connect with one of the following accounts





Login

Please wait while we redirect...

Views: 114   



With the help of module.exports feature you can move all the configurations into a separate file and you can import that into any file in your NodeJS application. Let say i have few configurations like port and MongoDB credentials that i want to put in a separate file named config.js Then the code looks like following.

config.js

var express = require('express');
var router = express.Router();

var config = {
  port : 5000,
  mongo : {
    production: 'mongodb://myuser:[email protected]:27017/db_user',
    local: 'mongodb://[email protected]:27017/db_user',
  },
  someOtherConfig: {
    foo: 'bar',
    age: 24
  }
}

module.exports = config;

As you can see in the above code, you have created a file named config.js and exported the config. Now you can import this module in any file using require and can start using it. For example if you want to refer this config in index.js where you start your Node application and connect to MongoDB, your code looks like following

The way you access in other files

var config = require('./config');
console.log('Port' + config.port);

More realistic examle usage

var express = require('express');
var app = express();

var MongoClient = require('mongodb').MongoClient;
var config = require('./config');

// Mongo Connection
db = {};
var mongoDbUri = config.mongo.local;
if(process && process.env && process.env.environment == 'production') {
   mongoDbUri = config.mongo.production;
}

var settings = {
      reconnectTries : Number.MAX_VALUE,
      autoReconnect : true
};

MongoClient.connect(mongoDbUri, settings, function(err, dbref) {
  if (!err) {
    console.log("Mongodb connected");
    db = dbref;
  }
});

// Start application
// Start App
app.set('port', (process.env.PORT || config.port));
app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

As shown in above example all you need to use the config is first import using require and then start using it.




On By


Top Tutorials

Top Questions

Top Articles

Top Blogs

Top News