-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (67 loc) · 2.25 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
'use strict';
const path = require('path');
const fs = require('fs');
const merge = require('lodash.merge');
const appPath = process.cwd();
class Config {
constructor(options) {
this.extensions = ['js', 'json'];
this.config = null;
options = options || global['jconf'] || {};
this.debug = options['debug'] || false;
this.baseName = options['baseName'] || 'config';
this.configPath = options['configPath'] || appPath;
this.excludeConfigName = options['excludeConfigName'] || false;
this._loadBase();
this._loadLocalConfig();
this._loadEnvConfig();
return this.config;
}
_findFile(baseName) {
let found = false;
this.extensions.forEach((ext) => {
if (found) {
return;
}
this.debug && console.log('Searching', baseName + '.' + ext, 'in', this.configPath);
if (fs.existsSync(path.join(this.configPath, baseName + '.' + ext))) {
this.debug && console.log('Loaded', baseName + '.' + ext, 'in', this.configPath);
found = require(path.join(this.configPath, baseName + '.' + ext));
}
});
return found;
}
_loadBase() {
this.config = this._findFile(this.baseName);
if (!this.config) {
console.warn('Configuration file is empty or wrong');
this.config = {};
}
if (!this.excludeConfigName) {
this.config._configName = 'base';
}
}
_loadLocalConfig() {
let localConfig = this._findFile(this.baseName + '.local');
if (localConfig && typeof localConfig === 'object') {
this.debug && console.info('Use local config file');
merge(this.config, localConfig);
if (!this.excludeConfigName) {
this.config._configName = 'local';
}
}
}
_loadEnvConfig() {
if (process.env.NODE_ENV && process.env.NODE_ENV.length > 0) {
let envConfig = this._findFile(this.baseName + '.' + process.env.NODE_ENV );
if (envConfig && typeof envConfig === 'object') {
this.debug && console.info('Use env file', this.baseName + '.' + process.env.NODE_ENV, 'config file');
merge(this.config, envConfig);
if (!this.excludeConfigName) {
this.config._configName = process.env.NODE_ENV;
}
}
}
}
}
module.exports = new Config();