首页 > 解决方案 > 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 配置解析器。

标签: node.jsiniconfigparser

解决方案


我会假设大多数 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)可以在应用程序运行之前,在部署时为您执行这种变量扩展。


推荐阅读