-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
101 lines (88 loc) · 2.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
var sys = require('sys'),
EventEmitter = require('events').EventEmitter,
p = require('child_process'),
path = require('path');
// By default node-config is going to look for 'conf' folder in curent directory.
// You can change that by changing the currentDirectory property
exports.currentDirectory = process.cwd();
function _addProperty(property_name, conf) {
Object.defineProperty(
exports,
property_name,
{
get: function() {
return conf[property_name];
},
enumerable: true,
configurable: true
}
);
}
function _processProperties(collection) {
for(var property in collection) {
if(collection.hasOwnProperty(property)) {
_addProperty(property, collection);
}
}
}
function _initInternal(hostname, callback) {
var conf = null,
conf_path = null;
//
// First of all, retrieve common properties
//
var conf_path = path.join(exports.currentDirectory,
'conf',
'common.js');
try {
conf = require(conf_path).conf;
_processProperties(conf);
} catch(err) {
sys.log('Unable to locate file ' + conf_path);
callback(err);
return;
}
//
// Then load host-specific ones.
// This is optional since there might be no host config.
//
try {
var conf_path = path.join(exports.currentDirectory,
'conf',
hostname + '.js')
conf = require(conf_path).conf;
_processProperties(conf);
} catch(err) {}
callback(null);
}
//
// You can force node-config to pick up config file different to your hostname,
// by supplying hostname parameter (omitting .js), i.e.
//
// initConfig(myCallback, 'my-host'); // assuming that ./conf/my-host.js exists
//
exports.initConfig = function(callback, hostname) {
//
// If hostname is set by user, do not invoke the 'hostname'
// command line tool. However still behave in the async fashion.
//
if(hostname) {
var eventEmitter = new EventEmitter();
eventEmitter.on('init',
function() {
_initInternal(hostname, callback);
}
);
eventEmitter.emit('init');
return;
}
// No hostname supplied, obtain hostname andproceed to initialisation.
hostnameProg = p.spawn('hostname');
hostnameProg.stdout.on('data', function(data) {
var _hostname = String(data).replace('\n', '');
_initInternal(_hostname, callback);
});
hostnameProg.stderr.on('data', function(data) {
callback(data);
});
}