【问题标题】:nodejs read .ini config filenodejs 读取 .ini 配置文件
【发布时间】:2020-08-08 13:10:20
【问题描述】:

我有一个配置文件。它以以下方式存储变量。

[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 配置解析器。

【问题讨论】:

    标签: node.js ini configparser


    【解决方案1】:

    我会假设大多数 ini 库不包含变量扩展功能,但是对于 lodash 原语,通用的“深度对象替换器”并不太复杂。

    我已将: 分隔符切换为.,因此hasget 可以直接查找值。

    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)可以在应用运行前、部署时为您执行此类变量扩展。

    【讨论】:

      猜你喜欢
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多