-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfigManager.js
69 lines (66 loc) · 1.82 KB
/
configManager.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
'use strict';
/**
* Resolve configuration by searching for common config paths:
* [app_dir]/config.js
* [app_dir]/config/[env].js
* [app_dir]/config/index.js
* [app_dir]/config/default.js
*/
var path = require('path');
var jsx = require('jsx');
var appRootDir = path.dirname(require.main.filename);
var runtimeInstances = {};
exports.load = function(options, env) {
var configPaths = ['config.js', 'config/' + env + '.js', 'config/index.js', 'config/default.js'];
var config;
if (typeof options === 'string' && options.length > 0) {
try {
var filename = path.join(appRootDir, options);
config = require(filename);
} catch(err) {
console.error('Cannot find or parse config file: %s', filename);
}
} else {
config = options;
}
if (!config) {
configPaths.some(function(val) {
try {
config = require(path.join(appRootDir, val))
} catch(err) {}
return true;
});
}
return config;
};
exports.runtime = function(id) {
id = id || '';
var runtime = runtimeInstances[id];
if (!runtime) {
runtime = {};
id = id ? ('.' + id) : '';
var filename = 'runtime' + id + '.json';
runtime.filepath = path.join(appRootDir, filename);
try {
runtime.config = jsx.fsx.sync.readJson(runtime.filepath);
} catch(err) {}
runtime.config = runtime.config || {};
runtime.isModified = false;
runtime.get = function(key) {
return runtime.config[key];
};
runtime.set = function(key, value) {
runtime.isModified = true;
runtime.config[key] = value;
};
runtime.save = function(force) {
if (runtime.isModified || force) {
jsx.fsx.sync.writeJson(runtime.filepath, runtime.config);
}
};
runtime.forEach = function(onEachItem) {
jsx.forEach(runtime.config, onEachItem);
};
}
return runtime;
}