Expressjs Configuration

expressjs

How can we handle configuration?

As you know, every node script is run as a console program. So, we can easily send command line arguments which will define the current environment. I wrapped that part in a separate module in order to write a test for it later. Here is the /config/index.js file:

var config = {
    local: {
        mode: 'local',
        port: 3000
    },
    staging: {
        mode: 'staging',
        port: 4000
    },
    production: {
        mode: 'production',
        port: 5000
    }
}
module.exports = function(mode) {
    return config[mode || process.argv[2] || 'local'] || config.local;
}

and in app.js:

var config = require('./config')();
...
http.createServer(app).listen(config.port, function(){
    console.log('Expressver listening on port ' + config.port);
});

To switch between the configurations, just add the environment at the end. For example:

node app.js staging
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License