A simple read-only configuration module for Node.js


There are already a few configuration modules available for Node.js. I built myself a simple read-only configuration module for Node.js as a learning experience. The module reads configuration information from a JSON file like the following

{
    "db":
    {
        "host": "localhost",
        "port": "1433"
    }
}

The module, called config.js, is initialized by calling the init method. The callback function passed to the init method is called when the initialization is complete. All the objects in the JSON file, which we have called config.json, can be accessed from the module object.

var fs = require('fs');

var config = function() {
    // constructor
}

config.prototype.init = function(file, cb) {
    fs.readFile(file, function (err, data) {
        if (err) {
            console.log(err);
            cb(-1);
        } else {
            var json = JSON.parse(data);
            for (o in json) {
                config.prototype[o] = json[o];
            }
            cb(0); // no error
        }
    });
}

module.exports = new config();

This is how the module can be used.

var config = require('./config.js');
config.init('config.json', function(resp) {
    if (resp != 0) {
        console.log('Could not load config file.');
        return;
    }
    console.log('host: ' + config.db.host);
    console.log('port: ' + config.db.port);
});

Once initialized, the module can be required by any script file of your Node.js application.

Why you don’t want to use the module above

Node.js already provides a neat mechanism to read JSON, you can simply require the JSON file:

var config = require('./config.json');
console.log(config.db.port);

The module system caches the file, so subsequent requires don’t parse the file again. If you need to read the file after it has been modified, you’ll need to use require.cache to delete it before invoking require.

delete require.cache('./config.json');

You can invoke require.cache when the file changes by using the watchFile function exported by the File System module.

2 thoughts on “A simple read-only configuration module for Node.js

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 )

Google+ photo

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

Connecting to %s