Add ability to specify configuration file on the command line
[KiwiIRC.git] / server / configuration.js
CommitLineData
cbe80532
JA
1var fs = require('fs'),
2 events = require('events'),
3 util = require('util');
1360a454
D
4
5var config_filename = 'config.js',
11dbb00f 6 config_dirs = ['/etc/kiwiirc/', __dirname + '/../'],
1360a454 7 environment = 'production',
11dbb00f 8 loaded_config = Object.create(null);
1360a454 9
cbe80532
JA
10var Config = function () {
11 events.EventEmitter.call(this);
12};
13util.inherits(Config, events.EventEmitter);
1360a454 14
da0ec4f7 15Config.prototype.loadConfig = function (manual_config_file) {
1360a454 16 var new_config,
33edb4a0
T
17 conf_filepath,
18 i;
1360a454 19
da0ec4f7
JA
20 if (manual_config_file) {
21 if (fs.existsSync(manual_config_file)) {
22 try {
23 if (fs.lstatSync(manual_config_file).isFile() === true) {
24 // Clear the loaded config cache
25 delete require.cache[require.resolve(manual_config_file)];
1360a454 26
da0ec4f7
JA
27 // Try load the new config file
28 new_config = require(manual_config_file);
29 }
30 } catch (e) {
31 console.log('An error occured parsing the config file ' + manual_config_file + ': ' + e.message);
32 process.exit(1);
1360a454 33 }
da0ec4f7
JA
34 } else {
35 console.log('Could not find config file ' + manual_config_file);
36 process.exit(1);
37 }
38 } else {
39 // Loop through the possible config paths and find a usable one
40 for (i = 0; i < config_dirs.length; i++) {
41 conf_filepath = config_dirs[i] + config_filename;
42
43 try {
44 if (fs.lstatSync(conf_filepath).isFile() === true) {
45 // Clear the loaded config cache
46 delete require.cache[require.resolve(conf_filepath)];
47
48 // Try load the new config file
49 new_config = require(conf_filepath);
50 break;
51 }
52 } catch (e) {
53 switch (e.code) {
54 case 'ENOENT': // No file/dir
55 break;
56 default:
57 console.log('An error occured parsing the config file ' + config_dirs[i] + config_filename + ': ' + e.message);
58 return false;
59 }
60 continue;
1360a454 61 }
1360a454
D
62 }
63 }
64
65 if (new_config) {
11dbb00f 66 loaded_config = new_config;
0a8a61ad 67 global.config = new_config[environment] || {};
cbe80532 68 this.emit('loaded');
11dbb00f 69 return loaded_config;
1360a454 70 } else {
11dbb00f 71 return false;
1360a454 72 }
cbe80532 73};
1360a454
D
74
75
76
cbe80532 77Config.prototype.setEnvironment = function (new_environment) {
11dbb00f 78 environment = new_environment;
1360a454
D
79};
80
81// Get the current config. Optionally for a different environment than currently set
cbe80532 82Config.prototype.get = function (specific_environment) {
11dbb00f
D
83 specific_environment = specific_environment || environment;
84
0a8a61ad 85 return loaded_config[specific_environment] || {};
1360a454
D
86};
87
cbe80532 88module.exports = new Config();