Node.js Application Configuration Files
December 13, 2010 6 Comments
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
}
Thanks, this really helped me!
Pingback: CodeBudo » Blog Archive » Application Configuration for Node.js
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”));
Thanks! Fixed.
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);
require() is good way to load settings, however I wanted to keep settings strictly as separate from the modules. Matter of taste methinks.