Configure Node.js application
« Tuesday, July 01, 2014 »

nodejs

Recently I searched for a way to configure my Node.js application but most solutions I found on StackOverflow kind of depend on environment variables. I believe that relying on environment variables is pretty awkward and could be a potential source of unexpected problems. I got used to explicitely use a configuration file for pyramid web applications. I decided to achieve a more or less similar approach for my nodejs server.

The reason why enviroment variables with things like dev, staging, production config doesn't make a lot of sense is that you can't have multiple production config file if you want to run multiple instance of the server on the same server.

The configuration

In Node.js, you can technically require JSON files but as other people mentionned. In a JSON file, you can't make use of commentaries. The other method would be to use a javascript file. The advantage of a javascript file is that you can have comments and you can also require other configs from the config file.

Example:

global.js

module.exports = {
    hotsname: "localhost",
    port: 8080
};

dev.js

var global_config = require("./configs/global");

module.exports = defaults(global_config, {
});

production.js

var global_config = require("./configs/global");

module.exports = defaults(global_config, {
    hostname: "www.example.com",
    port: 80
});

In theory, you could have configurations that inherit from other configurations. It's as simple as that. The defaults method could be a method that merge
both objects. It could be defined as such:

function defaults(source, extension) {
    var obj = Object.create(source)
        , key = undefined

    for(key in extension) {
        obj[key] = extension[key];
    }

    return obj;
}

Using the configuration

This is probably the part that could differ for many people. Instead of relying on environments variables. I rely on command line arguments. For my project, I decided to use yargs.

The code looks like this:

var yargs = require("yargs")
    , argv = yargs
        .usage("Usage: $0")
        .demand("c")
        .describe("c", "Config file")
        .alias("c", "config")
        .argv
    , config = require("./" + argv.config)

It could be made differently to handle errors when the file isn't found but in my case, since the script won't even go further without the config file. It doesn't really matter if Node.js stops at this point. But to make things nicer, we could handle the error when the file doesn't exist.

comments powered by Disqus

Copyright © 2015 Loïc Faure-Lacroix