Node.js Application Configuration Files

What is the best practice to make configuration file for your Node.js application? Writing property file parser or passing parameters at command line is cumbersome. One easy way to separate configuration and application code is by using “eval” statement. Define your configuration as simple Javascript associative array and load and eval it on app startup.

Example configuration file myconfig.js

settings = {
    a: 10,
    SOME_FILE: "/tmp/something"
}

Then at start of your application

fs = require('fs');
eval(fs.readFileSync('myconfig.js', encoding="ascii"));

Now ‘settings’ object can be used as your program settings. e.g.

var mydata = fs.readFileSync(settings.SOME_FILE);
for( i = 0 ; i < settings.a ; i++) {
   // do something
}
Advertisement

6 Responses to Node.js Application Configuration Files

  1. Thanks, this really helped me!

  2. Pingback: CodeBudo » Blog Archive » Application Configuration for Node.js

  3. There is a small typo in your post, the code to read a file and eval should be:

    eval(fs.readFileSync(‘myconfig.js’, encoding=”ascii”));

  4. Nick says:

    Why not just store your settings as a module? Then you can utilize require() to keep a single reference to it.

    appSettings.js:
    exports.settings =
    { settingName: ‘this is cool!’
    , settingName2: true
    }

    Usage:
    var settings = require(‘./appSettings.js’).settings;

    console.log(settings.settingName);

    • tikonen says:

      require() is good way to load settings, however I wanted to keep settings strictly as separate from the modules. Matter of taste methinks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.