Commit | Line | Data |
---|---|---|
1360a454 D |
1 | var fs = require('fs'); |
2 | ||
3 | var config_filename = 'config.js', | |
11dbb00f | 4 | config_dirs = ['/etc/kiwiirc/', __dirname + '/../'], |
1360a454 | 5 | environment = 'production', |
11dbb00f | 6 | loaded_config = Object.create(null); |
1360a454 D |
7 | |
8 | ||
9 | function loadConfig() { | |
10 | var new_config, | |
33edb4a0 T |
11 | conf_filepath, |
12 | i; | |
1360a454 D |
13 | |
14 | // Loop through the possible config paths and find a usable one | |
33edb4a0 | 15 | for (i = 0; i < config_dirs.length; i++) { |
1360a454 D |
16 | conf_filepath = config_dirs[i] + config_filename; |
17 | ||
18 | try { | |
19 | if (fs.lstatSync(conf_filepath).isFile() === true) { | |
20 | // Clear the loaded config cache | |
21 | delete require.cache[require.resolve(conf_filepath)]; | |
22 | ||
23 | // Try load the new config file | |
24 | new_config = require(conf_filepath); | |
1360a454 D |
25 | break; |
26 | } | |
27 | } catch (e) { | |
28 | switch (e.code) { | |
29 | case 'ENOENT': // No file/dir | |
30 | break; | |
31 | default: | |
32 | console.log('An error occured parsing the config file ' + config_dirs[i] + config_filename + ': ' + e.message); | |
33 | return false; | |
34 | } | |
35 | continue; | |
36 | } | |
37 | } | |
38 | ||
39 | if (new_config) { | |
11dbb00f | 40 | loaded_config = new_config; |
0a8a61ad | 41 | global.config = new_config[environment] || {}; |
11dbb00f | 42 | return loaded_config; |
1360a454 | 43 | } else { |
11dbb00f | 44 | return false; |
1360a454 D |
45 | } |
46 | } | |
47 | ||
48 | ||
49 | ||
50 | module.exports.setEnvironment = function (new_environment) { | |
11dbb00f | 51 | environment = new_environment; |
1360a454 D |
52 | }; |
53 | ||
54 | // Get the current config. Optionally for a different environment than currently set | |
55 | module.exports.get = function (specific_environment) { | |
11dbb00f D |
56 | specific_environment = specific_environment || environment; |
57 | ||
0a8a61ad | 58 | return loaded_config[specific_environment] || {}; |
1360a454 D |
59 | }; |
60 | ||
33edb4a0 | 61 | module.exports.loadConfig = loadConfig; |