Configuration is always a chore, a simple thing you have to do, and keep reinventing every time you start a new project.
I usually have the following setup:
I have one configuration file per domain and several domains. A domain may be “www”, “couchdb” or a remote service that requires some parametrization like Postmark.
These are JSON files that lie in some directory.
Now, I want to be able to override them for each environment the application works on. I may have a “development” environment, a “test” environment, a “staging” environment and a “production” environment. I may even have different development environment configurations depending on the developer.
I want, for each of these environments, to be able to slightly tweak each configuration for some domains. For instance, I use localhost for Redis in my development environment, but redis.hostname.com in my production one. I want to be able to just specify the differences, not the whole configuration again, because soon that starts to be unmaintainable.
Looks simple, right? I searched through some existing Node.js modules that manage configuration, and had none that answered these requirements.
So I came up with Konphyg.
Installing
$ npm install konphyg
Using
First you import konphyg and give it a source dir like this:
var config = require('konphyg')(__dirname + "/config");
Then you create the “config” dir and put a configuration file for each domain. For instance, for the “postmark” domain, I can have:
{
"host": "api.postmarkapp.com"
, "ssl": false
, "api_key": "myapikey"
}
I place this file inside the “config” dir and name it “postmark.json”.
Now, for my development environment I need to specify my API key. So, inside the config dir I place the file “postmark.development.json” with just this:
{
"api_key": "ABCDEFGHI"
}
Then, on my Node code, if I do:
console.log(config("postmark"));
I get:
{
"host": "api.postmarkapp.com"
, "ssl": false
, "api_key": "ABCDEFGHI"
}
Simple, right?
Konphyg can also handle deep object nesting in your configuration file, and it will correctly merge the environment-specific configuration with the base one.
Konphyg uses the NODE_ENV environment variable to determine the environment. If not present, it defaults to “development”.
-
buy-steroids--uk reblogged this from metaduck