nconf
1.是什么
Hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging.
对node.js中 文件、环境变量、命令行参数以及原子对象整合 提供分层配置。
2.能干什么
它被设计,使用简单的key-value模式,来进行便捷本地或是远程信息的存储。
案例
-
安装ncong
npm install --save nconf
-
在模块中引用 nconf
var nconf = require('ncong'); # es 6 import nconf from 'nconf';
-
初始化nconf
# # Setup nconf to use (in-order): # 1\. Command-line arguments ## 1.通过 .argv() 存储命令行参数信息 # 2\. Environment variables ## 2.通过 .env() 存储环境变量信息 # 3\. A file located at 'path/to/config.json' ## 3. 通过file({file: 'path'}) 方式加载json 并存储配置信息 nconf.argv() .env() .file({ file: 'path/to/config.json' });
-
setter与getter
# setter 将变量存入 nconf # key支持按 : 分层, 如下面的 database:host database:port, 通过get database 可以拿到下面的host与port # nconf.set(key, value); nconf.set('database:host', '127.0.0.1'); nconf.set('database:port', 5432); # getter 从nconf中获取变量信息 # nconf.get(key); console.info('database: ', nconf.get('databse'));
-
将nconf保存至本地磁盘
nconf.save(function (err) { fs.readFile('path/to/your/config.json', function (err, data) { console.dir(JSON.parse(data.toString())) }); });
API
-
nconf.argv(options) Loads
process.argv
using yargs. Ifoptions
is supplied it is passed along to yargs.nconf.argv();
-
nconf.env(options) Loads
process.env
into the hierarchy.nconf.env()
-
nconf.file(options) Loads the configuration data at options.file into the hierarchy.
nconf.file({file: 'filepath'});
-
nconf.defaults(options) Loads the data in options.store into the hierarchy.
nconf.defaults({ 'THREE': 'hello three' });
-
nconf.overrides(options) Loads the data in options.store into the hierarchy.
nconf.overrides({ 'THREE': 'hello three' });