Nodejs Confman - 针对「Node 应用」的配置文件加载模块

Nodejs Confman - 针对「Node 应用」的配置文件加载模块

一句话介绍

confman 是一个强大的配置文件加载器,无论你喜欢 yaml 、 cson 、 json 、 properties 、 plist 、 ini 、 toml 、 xml 还是 js ,都能满足你的愿望,并且更加简单、更加强大。

npm version Build Status

支持的特性

  • 支持多种配置文件格式,默认包括 yaml/cson/json/properties/plist/ini/toml/xml/js
  • 支持配置文件相互引用,无论何种格式都可以「引用其它任意格式」的配置文件
  • 支持「基于目录」的多文件配置
  • 支持「环境配置」,区分加载生产、测试等不同的配置
  • 可以非常方便的「扩展」新的配置文件格式
  • 可以「混合使用」不同的配置文件格式

现在就安装

$ npm install confman --save

来几个示例

不同的环境配置

目录

app
├── index.js
├── config.dev.yaml
├── config.prod.yaml
└── config.yaml

index.js

const confman = require('confman');
const configs = confman.load(`${__dirname}/config`);
console.log(configs);

启动应用

$ NODE_ENV=prod node index.js 

通过指定 NODE_ENV 可以加载指定的「环境配置文件 config.prod.ymal 」,并和「默认配置 config.yaml 」进行合并, 如果有相同的配置,「环境配置会覆盖默认配置」

配置文件相互引用

文件一: test1.yaml

name: test1
#可以使用 $require 引用其它文件
child: $requrie ./test2

文件二: test2.json

{
  "name": "test2",
   "child": "$require other-file"
}

$require 可以在任意支持的格式的配置文件中使用

基于目录的多文件配置

目录结构

├── config
│   ├── conn.yaml
│   ├── index.yaml
│   └── mvc.yaml
├── config.dev
│   └── conn.yaml
├── config.prod
│   └── conn.yaml
└── index.js

index.js

const confman = require('confman');
const configs = confman.load(`${__dirname}/config`);
console.log(configs);

扩展新格式

其实,多数情况你不需要这么做,如果确实有需要,你可这样编写一个自定义 loader

module.exports = {
  extname: '.xxx',
  load: function (configPath) {
    //...
    return configs;
  }
};

添加自定义 loader

confman.loaders.push(require('your-loader-path'));

自定义扩展名

方式一,映射到一个已经支持(添加注册到 confman )的 loader

confman.loaders.push({
  extname: '.xxx',
  loader: '.yaml'
});

方式二,映射到一个自定义 loader

confman.loaders.push({
  extname: '.xxx',
  loader: require('your-loader-path')
});

现在或将来有可能会用到?那你应该去加个 Star
GitHub : https://github.com/Houfeng/confman


2 回复

star 已送


针对「Node 应用」的配置文件加载模块,Node.js 社区提供了多种解决方案,其中 confman 是一个较为流行的选择,尽管它不是 Node.js 官方的库,但功能强大且灵活。以下是一个简单的示例,展示如何使用一个自定义的或流行的配置文件加载模块(假设名为 confman,但请注意实际使用时可能需要查找具体库的文档和安装方法,因为没有一个广泛认知的名为 confman 的标准库)。

首先,确保你的项目已经安装了所需的库(如果有一个名为 confman 的库):

npm install confman

然后,你可以在你的 Node.js 应用中这样使用:

const confman = require('confman'); // 假设 confman 是一个实际存在的库

// 加载配置文件,假设配置文件为 JSON 格式
confman.load('config.json', (err, config) => {
    if (err) {
        console.error('Failed to load config:', err);
        process.exit(1);
    }
    console.log('Loaded config:', config);

    // 使用配置
    const port = config.server.port;
    console.log(`Server will run on port ${port}`);
});

在上面的代码中,我们假设 confman 提供了一个 load 方法来异步加载配置文件。实际使用中,你可能需要根据 confman 的具体 API 文档来调整代码。

如果 confman 不是一个实际存在的库,你可能需要查看像 confignconfdotenv 等流行的配置文件加载库,这些库都提供了丰富的功能来加载和处理配置文件。

回到顶部