j_quelly
j_quelly

Reputation: 1449

express app settings stored in separate file

Currently I set my express app settings in app.js like so:

app.set('siteCategoryNo', '900');
app.set('brandCompanyName', 'Website Name');
app.set('brandDomainName', 'website.com');

Instead I would like to store them in a separate file app-config.js like so:

/*  
 * app-config.js
 */
module.exports = function () {

    var appSettings = {

        settings: [{
            key: 'siteCategoryNo',
             val: '900'
        }, {
            key: 'brandCompanyName',
            val: 'website name'
        }, {
            key: 'brandDomainName',
            val: 'website.com'
        }]

        // all other settings omitted

    }

    return appSettings;

};

This is what app.js would look like:

// all other code omitted
var configSettings = require('./app-config.js')();

for (var i = 0; i <= configSettings.settings.length; i++) {
    var applicationSettings = configSettings.settings.pop();
    app.set(applicationSettings.key, applicationSettings.val);
}

I'm doing things this way because I am building a nearly identical website with another developer, but we have some different settings and routes. We're hoping this will make merging easier.

The loop over the associative array (if that's what you call it) works only when the object array is in the app.js file. I'd like to separate this into app-config.js, but as soon as I do none of my vars are set.

Is this possible?

Upvotes: 0

Views: 240

Answers (1)

MinusFour
MinusFour

Reputation: 14423

You could do it like this:

module.exports = function (app) {

    var appSettings = {

        settings: [{
            key: 'siteCategoryNo',
             val: '900'
        }, {
            key: 'brandCompanyName',
            val: 'website name'
        }, {
            key: 'brandDomainName',
            val: 'website.com'
        }]

        // all other settings omitted

    }

    appSettings.settings.forEach(function(setting){
      app.set(setting.key, setting.val);
      });
    return app;
};

And then from app.js:

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

Upvotes: 1

Related Questions