1 var fs
= require('fs'),
2 events
= require('events'),
3 util
= require('util'),
4 path
= require('path'),
5 winston
= require('winston');
7 var config_filename
= 'config.js',
8 config_dirs
= ['/etc/kiwiirc/', __dirname
+ '/../'],
9 environment
= 'production',
10 loaded_config
= Object
.create(null);
12 var Config = function () {
13 events
.EventEmitter
.call(this);
15 util
.inherits(Config
, events
.EventEmitter
);
17 Config
.prototype.loadConfig = function (manual_config_file
) {
22 if ((manual_config_file
) || (this.manual_config_file
)) {
23 manual_config_file
= path
.resolve(path
.normalize(manual_config_file
|| this.manual_config_file
));
24 if (fs
.existsSync(manual_config_file
)) {
26 if (fs
.lstatSync(manual_config_file
).isFile() === true) {
27 // Clear the loaded config cache
28 delete require
.cache
[require
.resolve(manual_config_file
)];
30 // Try load the new config file
31 new_config
= require(manual_config_file
);
33 // Save location of configuration file so that we can re-load it later
34 this.manual_config_file
= manual_config_file
;
37 winston
.error('An error occured parsing the config file %s: %s', manual_config_file
, e
.message
);
41 winston
.error('Could not find config file %s', manual_config_file
);
45 // Loop through the possible config paths and find a usable one
46 for (i
= 0; i
< config_dirs
.length
; i
++) {
47 conf_filepath
= config_dirs
[i
] + config_filename
;
50 if (fs
.lstatSync(conf_filepath
).isFile() === true) {
51 // Clear the loaded config cache
52 delete require
.cache
[require
.resolve(conf_filepath
)];
54 // Try load the new config file
55 new_config
= require(conf_filepath
);
60 case 'ENOENT': // No file/dir
63 winston
.warn('An error occured parsing the config file %s%s: %s', config_dirs
[i
], config_filename
, e
.message
);
72 loaded_config
= new_config
;
73 global
.config
= new_config
[environment
] || {};
83 Config
.prototype.setEnvironment = function (new_environment
) {
84 environment
= new_environment
;
87 // Get the current config. Optionally for a different environment than currently set
88 Config
.prototype.get = function (specific_environment
) {
89 specific_environment
= specific_environment
|| environment
;
91 return loaded_config
[specific_environment
] || {};
94 module
.exports
= new Config();