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

2016-07-26 23:37:47 +08:00
 houfeng

一句话介绍

confman 是一个强大的配置文件加载器,无论你喜欢 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

2154 次点击
所在节点    Node.js
1 条回复
phoenixlzx
2016-07-26 23:40:56 +08:00
star 已送

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/295143

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX