Merge branch 'settings' of https://github.com/M2Ys4U/KiwiIRC into settings
[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
cbe80532 15Config.prototype.loadConfig = function () {
1360a454 16 var new_config,
33edb4a0
T
17 conf_filepath,
18 i;
1360a454
D
19
20 // Loop through the possible config paths and find a usable one
33edb4a0 21 for (i = 0; i < config_dirs.length; i++) {
1360a454
D
22 conf_filepath = config_dirs[i] + config_filename;
23
24 try {
25 if (fs.lstatSync(conf_filepath).isFile() === true) {
26 // Clear the loaded config cache
27 delete require.cache[require.resolve(conf_filepath)];
28
29 // Try load the new config file
30 new_config = require(conf_filepath);
1360a454
D
31 break;
32 }
33 } catch (e) {
34 switch (e.code) {
35 case 'ENOENT': // No file/dir
36 break;
37 default:
38 console.log('An error occured parsing the config file ' + config_dirs[i] + config_filename + ': ' + e.message);
39 return false;
40 }
41 continue;
42 }
43 }
44
45 if (new_config) {
11dbb00f 46 loaded_config = new_config;
0a8a61ad 47 global.config = new_config[environment] || {};
cbe80532 48 this.emit('loaded');
11dbb00f 49 return loaded_config;
1360a454 50 } else {
11dbb00f 51 return false;
1360a454 52 }
cbe80532 53};
1360a454
D
54
55
56
cbe80532 57Config.prototype.setEnvironment = function (new_environment) {
11dbb00f 58 environment = new_environment;
1360a454
D
59};
60
61// Get the current config. Optionally for a different environment than currently set
cbe80532 62Config.prototype.get = function (specific_environment) {
11dbb00f
D
63 specific_environment = specific_environment || environment;
64
0a8a61ad 65 return loaded_config[specific_environment] || {};
1360a454
D
66};
67
cbe80532 68module.exports = new Config();