支持传入配置文件名作为参数

This commit is contained in:
陆柯 2022-04-24 16:42:08 +08:00
parent d3f694b10b
commit 8b945b405d

View File

@ -6,77 +6,53 @@ const deepmerge = require('deepmerge')
const my = { secretKeys:[] } const my = { secretKeys:[] }
module.exports = { module.exports = {
mergeConfig(rawConfig) { mergeConfig({rawConfig={}, envarFiles=['./envar-base-basic.js', './envar-base-custom.js', './envar-base-secret.js']} = {}) {
if (!global.envar) { if (!global.envar) {
global.envar = rawConfig global.envar = rawConfig
// 不知为何必须定义成全局变量才能保证多次require只执行一次。 // 不知为何必须定义成全局变量才能保证多次require只执行一次。
console.info('<<<<<<<< Merging Environment Configuration (依次载入基础配置、用户配置、机密配置、命令行参数) <<<<<<<<')
// 配置参数(按优先级从低到高): console.info('<<<<<<<< Collecting Environment Configuration <<<<<<<<')
// envar-base-basic.js: 系统常量(全大写) 以及 默认参数(小写开头驼峰式)
// envar-base-custom.js: 用户或应用自定义参数。本文件不应纳入版本管理。
// envar-base-secret.js: 机密参数例如哈希盐webtoken密钥等等。本文件绝对不能纳入版本管理。
// 命令行参数
console.info('(1) Loading Configuration Files (读取配置文件)') console.info('- Loading Configuration Files (读取配置文件)')
let configFile
if (fs.existsSync((configFile = path.join(process.cwd(), './envar-base-basic.js')))) { for (let configFile of envarFiles){
global.envar = deepmerge(global.envar, require(configFile)) if (fs.existsSync(path.resolve(configFile))) {
global.envar = deepmerge(global.envar, require(path.resolve(configFile)))
console.info(` - ${configFile} is loaded.`) console.info(` - ${configFile} is loaded.`)
} else { } else {
console.warn(` - ${configFile} is missing.`) console.warn(` - ${configFile} is missing.`)
} }
}
global.envar.prodev = global.envar.prodev || process.env.NODE_ENV || 'development' // server = require('express')(); server.get('env') === server.settings.env === process.env.NODE_ENV global.envar.prodev = global.envar.prodev || process.env.NODE_ENV || 'development' // server = require('express')(); server.get('env') === server.settings.env === process.env.NODE_ENV
if (global.envar.prodev === 'production' && global.envar.production) { if (global.envar.prodev === 'production' && global.envar.production) {
console.info(' - Loading Production Configuration (加载生产环境配置)') console.info('- Applying Production Configuration (加载生产环境配置)')
global.envar = deepmerge(global.envar, global.envar.production) global.envar = deepmerge(global.envar, global.envar.production) // 注意objectMerge后产生了一个新的对象而不是在原来的Config里添加
delete global.envar.production delete global.envar.production
} }
if (fs.existsSync((configFile = path.join(process.cwd(), './envar-base-custom.js')))) { console.info('- Loading Command Line Parameters (载入命令行参数)')
// 如果存在,覆盖掉 envar-base-basic.js 里的默认参数
global.envar = deepmerge(global.envar, require(configFile)) // 注意objectMerge后产生了一个新的对象而不是在原来的Config里添加
console.info(`${configFile} is loaded.`)
} else {
console.warn(` - ${configFile} is missing.`)
}
if (fs.existsSync((configFile = path.join(process.cwd(), './envar-base-secret.js')))) {
// 如果存在,覆盖掉 envar-base-basic.js 和 envar-base-custom.js 里的参数
let secretConfig = require(configFile)
my.secretKeys = Object.keys(secretConfig)
global.envar = deepmerge(global.envar, secretConfig)
console.info(` - ${configFile} is loaded.`)
} else {
console.warn(` - ${configFile} is missing.`)
}
global.envar = global.envar || {}
console.info('(2) Loading Command Line Parameters (载入命令行参数)')
commander.version(global.envar.Base_Version || '0.0.1', '-v, --version') // 默认是 -V。如果要 -v就要加 '-v --version' commander.version(global.envar.Base_Version || '0.0.1', '-v, --version') // 默认是 -V。如果要 -v就要加 '-v --version'
for (let [key, param, desc] of global.envar.Commander_Option_List || []) { for (let [key, param, desc] of global.envar.Commander_Option_List || []) {
commander.option(param, `${desc} Default = "${global.envar[key]}"`) commander.option(param, `${desc} Default = "${global.envar[key]}"`)
} }
commander.parse(process.argv) commander.parse(process.argv)
console.log('(3) Merging Command Line Parameters into Configuration (把命令行参数合并入配置)')
for (let key in commander) {
if (typeof commander[key] === 'string' && !/^_/.test(key)) {
global.envar[key] = commander[key] || global.envar[key]
}
}
}
delete global.envar.Commander_Option_List // do not print Commander_Option_List to console delete global.envar.Commander_Option_List // do not print Commander_Option_List to console
console.log('>>>>>>>> Merged Environment Configuration >>>>>>>>') console.log('- Merging Command Line Parameters into Configuration (把命令行参数值合并入配置)')
for (let key in commander) {
if (!/^_/.test(key) && typeof commander[key] === 'string') { // commander 自带了一批 _开头的属性过滤掉
global.envar[key] = commander[key]
}
}
}
console.log('>>>>>>>> Collected Environment Configuration >>>>>>>>')
return global.envar return global.envar
}, },
getDynamicConfig(dynamicConfigFile='envar-base-dynamic.js') { // dynamicConfigFile should be absolute or relative to the node process's dir. getDynamicConfig(dynamicConfigFile='envar-base-dynamic.js') { // dynamicConfigFile should be absolute or relative to the node process's dir.
const fullpath = path.join(process.cwd(), dynamicConfigFile) const fullpath = path.resolve(dynamicConfigFile)
if (fs.existsSync(fullpath)) { if (fs.existsSync(fullpath)) {
delete require.cache[require.resolve(fullpath)] // delete require.cache[fullpath] 不起作用 delete require.cache[require.resolve(fullpath)] // delete require.cache[fullpath] 不起作用
return require(fullpath) return require(fullpath)
@ -86,10 +62,10 @@ module.exports = {
}, },
maskSecret() { maskSecret() {
let envar = JSON.parse(JSON.stringify(global.envar)) let envar = JSON.parse(JSON.stringify(global.envar)) // 复制一份,避免污染
for (let key in envar) { for (let key in envar) {
if (my.secretKeys.includes(key)) { if (/^SECRET_/.test(key)) {
envar[key] = '***confidential***' envar[key] = '*** confidentical ***'
} }
} }
return envar return envar