node.js - nodejs 读取 .ini 配置文件
问题描述
我有一个配置文件。它具有以下列方式存储的变量。
[general]
webapp=/var/www
data=/home/data
[env]
WEBAPP_DEPLOY=${general:webapp}/storage/deploy
SYSTEM_DEPLOY=${general:data}/deploy
如您所见,它有 2 个部分 general 和 env。部分 env 使用来自一般部分的变量。
所以我想把这个文件读入一个变量。先说配置。这是我希望配置对象看起来像:
{
general: {
webapp: '/var/www',
data: '/home/data'
},
env: {
WEBAPP_DEPLOY: '/var/www/storage/deploy',
SYSTEM_DEPLOY: '/home/data/deploy'
}
}
我一般我正在寻找一个支持字符串插值的 nodejs 配置解析器。
解决方案
我会假设大多数 ini 库不包含变量扩展功能,但是对于 lodash 原语,通用的“深度对象替换器”并不太复杂。
我已经为so has:
切换了分隔符,并且get可以直接查找值。.
const { get, has, isPlainObject, reduce } = require('lodash')
// Match all tokens like `${a.b}` and capture the variable path inside the parens
const re_token = /\${([\w$][\w\.$]*?)}/g
// If a string includes a token and the token exists in the object, replace it
function tokenReplace(value, key, object){
if (!value || !value.replace) return value
return value.replace(re_token, (match_string, token_path) => {
if (has(object, token_path)) return get(object, token_path)
return match_string
})
}
// Deep clone any plain objects and strings, replacing tokens
function plainObjectReplacer(node, object = node){
return reduce(node, (result, value, key) => {
result[key] = (isPlainObject(value))
? plainObjectReplacer(value, object)
: tokenReplace(value, key, object)
return result
}, {})
}
> plainObjectReplacer({ a: { b: { c: 1 }}, d: 'wat', e: '${d}${a.b.c}' })
{ a: { b: { c: 1 } }, d: 'wat', e: 'wat1' }
您会发现大多数配置管理工具(如ansible)可以在应用程序运行之前,在部署时为您执行这种变量扩展。
推荐阅读
- javascript - 在我的照片中,我无法将星星旋转成圆圈
- vue.js - 多个验证插件问题
- sql - SQL - 将具有周范围的行拆分为多行
- c++ - 如何翻译快捷键
- excel - 如何计算每列连续突出显示的单元格?
- reactjs - 快递总是路由到\
- angular - 角度通用的ngx-openlayers问题
- visual-studio-code - 错误:导入“https://deno.land/std@v0.51.0/io/util.ts”失败:404 未找到
- java - java - 如何通过UDP连接向java中的数据报包添加序列号?
- html - 如何使用文本和图标创建导航栏?