nconf初识

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

  1. nconf.argv(options) Loads process.argv using yargs. If options is supplied it is passed along to yargs.

    nconf.argv();
    
  2. nconf.env(options) Loads process.env into the hierarchy.

    nconf.env()
    
  3. nconf.file(options) Loads the configuration data at options.file into the hierarchy.

    nconf.file({file: 'filepath'});
    
  4. nconf.defaults(options) Loads the data in options.store into the hierarchy.

    nconf.defaults({
        'THREE': 'hello three'
    });
    
  5. nconf.overrides(options) Loads the data in options.store into the hierarchy.

    nconf.overrides({
        'THREE': 'hello three'
    });
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,516评论 0 13
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,936评论 0 0
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,921评论 0 38
  • 冬至昼最短, 红阳铺满脸。 暂欢随日逝, 再见是何年?
    风筝_5c59阅读 300评论 19 20