forked from lsongdev/kelp-config
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (67 loc) · 1.57 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
'use strict';
const fs = require('fs');
const path = require('path');
const extend = require('extend');
const resolve = require('resolve');
const pkg = require('./package');
const dir = process.env.CONFIG_DIR || 'config';
const env = process.env.NODE_ENV || 'development';
/**
* [print message]
* @param {[type]} msg [message]
*/
function print(msg){
console.error('\x1b[31m[%s] %s\x1b[0m', pkg.name, msg);
};
/**
* load config
* @param {[type]} name [env filename]
* @return {[type]} [config]
*/
function load(name){
var filename = '';
try{
filename = resolve.sync(name, {
moduleDirectory : dir,
basedir : process.cwd(),
extensions : ['.js', '.json', '.node', '.yaml', '.yml'],
});
}catch(e){}
if(filename){
if(/\.ya?ml$/.test(filename)){ // yaml loader
var content = fs.readFileSync(filename, 'utf8');
try{
return require('js-yaml').safeLoad(content);
}catch(e){
print('`js-yaml` is required when you use yaml files .');
}
}else{ // js, json, and otherwise .
try{
return require(filename);
}catch(e){
print('cannot read config from: ' + filename);
}
}
}
return {};
};
/**
* [command-line arguments supports]
*/
var argv = {};
if(process.argv.length > 2){
try{
argv = require('minimist')(process.argv.slice(2));
delete argv[ '_' ];
}catch(e){
print('`minimist` is required when you use command-line arguments .');
}
};
/**
* [merge config]
*/
module.exports = extend(true,
load('default'),
load(env),
argv
);