@acceleratxr/nconf 中文文档教程

发布于 3年前 浏览 19 项目主页 更新于 3年前

nconf

版本 npmnpm 下载构建状态覆盖范围Dependencies

具有文件、环境变量、命令行参数和原子对象合并的分层 node.js 配置。

Example

使用 nconf 很简单; 它被设计成一个简单的键值存储,同时支持本地和远程存储。 键由 : 命名空间和分隔。 让我们深入了解示例用法:

  // sample.js
  var nconf = require('nconf');

  //
  // Setup nconf to use (in-order):
  //   1. Command-line arguments
  //   2. Environment variables
  //   3. A file located at 'path/to/config.json'
  //
  nconf.argv()
   .env()
   .file({ file: 'path/to/config.json' });

  //
  // Set a few variables on `nconf`.
  //
  nconf.set('database:host', '127.0.0.1');
  nconf.set('database:port', 5984);

  //
  // Get the entire database object from nconf. This will output
  // { host: '127.0.0.1', port: 5984 }
  //
  console.log('foo: ' + nconf.get('foo'));
  console.log('NODE_ENV: ' + nconf.get('NODE_ENV'));
  console.log('database: ' + nconf.get('database'));

  //
  // Save the configuration object to disk
  //
  nconf.save(function (err) {
    require('fs').readFile('path/to/your/config.json', function (err, data) {
      console.dir(JSON.parse(data.toString()))
    });
  });

如果您运行以下脚本:

  $ NODE_ENV=production node sample.js --foo bar

输出将是:

  foo: bar
  NODE_ENV: production
  database: { host: '127.0.0.1', port: 5984 }

Hierarchical configuration

即使是在生产环境中运行的微不足道的应用程序,配置管理也会很快变得复杂。 nconf 通过使您能够为不同的配置源设置一个没有默认值的层次结构来解决这个问题。 您附加这些配置源的顺序决定了它们在层次结构中的优先级。让我们看一下您可用的选项

  1. nconf.argv(options) Loads process.argv using yargs. If options is supplied it is passed along to yargs.
  2. nconf.env(options) Loads process.env into the hierarchy.
  3. nconf.file(options) Loads the configuration data at options.file into the hierarchy.
  4. nconf.defaults(options) Loads the data in options.store into the hierarchy.
  5. nconf.overrides(options) Loads the data in options.store into the hierarchy.

一个合理的默认值可能是:

  var nconf = require('nconf');

  //
  // 1. any overrides
  //
  nconf.overrides({
    'always': 'be this value'
  });

  //
  // 2. `process.env`
  // 3. `process.argv`
  //
  nconf.env().argv();

  //
  // 4. Values in `config.json`
  //
  nconf.file('/path/to/config.json');

  //
  // Or with a custom name
  // Note: A custom key must be supplied for hierarchy to work if multiple files are used.
  //
  nconf.file('custom', '/path/to/config.json');

  //
  // Or searching from a base directory.
  // Note: `name` is optional.
  //
  nconf.file(name, {
    file: 'config.json',
    dir: 'search/from/here',
    search: true
  });

  //
  // 5. Any default values
  //
  nconf.defaults({
    'if nothing else': 'use this value'
  });

API Documentation

nconf 的顶层nconf.Provider 的一个实例,为您将这一切抽象成一个简单的 API。

nconf.add(name, options)

添加具有指定 nameoptions 的新商店。 如果未设置 options.type,则将使用 name

  nconf.add('supplied', { type: 'literal', store: { 'some': 'config' } });
  nconf.add('user', { type: 'file', file: '/path/to/userconf.json' });
  nconf.add('global', { type: 'file', file: '/path/to/globalconf.json' });

nconf.any(names, callback)

给定一组键名,获取发现的第一个键的值。 键名可以作为单独的参数给出 或作为数组。 如果最后一个参数是一个函数,它将被调用并返回结果; 否则,返回该值。

  //
  // Get one of 'NODEJS_PORT' and 'PORT' as a return value
  //
  var port = nconf.any('NODEJS_PORT', 'PORT');

  //
  // Get one of 'NODEJS_IP' and 'IPADDRESS' using a callback
  //
  nconf.any(['NODEJS_IP', 'IPADDRESS'], function(err, value) {
    console.log('Connect to IP address ' + value);
  });

nconf.use(name, options)

nconf.add 类似,不同之处在于它可以在提供新选项时替换现有存储

  //
  // Load a file store onto nconf with the specified settings
  //
  nconf.use('file', { file: '/path/to/some/config-file.json' });

  //
  // Replace the file store with new settings
  //
  nconf.use('file', { file: 'path/to/a-new/config-file.json' });

nconf.remove(name)

删除具有指定 name 的存储。 存储在该级别的配置将不再用于查找。

  nconf.remove('file');

nconf.required(keys)

声明一组字符串键是强制性的,如果有任何缺失则抛出错误。

  nconf.defaults({
    keya: 'a',
  });

  nconf.required(['keya', 'keyb']);
  // Error: Missing required keys: keyb

您还可以在需要时链接 .required() 调用。 例如,当一个配置依赖于另一个配置存储时

config
  .argv()
  .env()
  .required([ 'STAGE']) //here you should have STAGE otherwise throw an error
  .file( 'stage', path.resolve( 'configs', 'stages', config.get( 'STAGE' ) + '.json' ) )
  .required([ 'OAUTH:redirectURL']) // here you should have OAUTH:redirectURL, otherwise throw an error
  .file( 'oauth', path.resolve( 'configs', 'oauth', config.get( 'OAUTH:MODE' ) + '.json' ) )
  .file( 'app', path.resolve( 'configs', 'app.json' ) )
  .required([ 'LOGS_MODE']) // here you should haveLOGS_MODE, otherwise throw an error
  .add( 'logs', {
    type: 'literal',
    store: require( path.resolve( 'configs', 'logs', config.get( 'LOGS_MODE' ) + '.js') )
  } )
  .defaults( defaults );

Storage Engines

Memory

一个简单的内存存储引擎,用于存储配置的嵌套 JSON 表示。 要使用此引擎,只需使用适当的参数调用 .use()。 所有对 .get().set().clear().reset() 的调用方法是同步的,因为我们只处理内存中的对象。

所有内置存储引擎都继承自 Memory 存储。

基本用法:

  nconf.use('memory');

Options

下面定义的选项适用于所有继承自 Memory 的存储引擎。

accessSeparator: string (default: ':')

定义用于使用 get()set() 方法获取或设置数据的分隔符。 即使更改了,默认的“冒号”分隔符也将可用,除非明确禁用(参见 disableDefaultAccessSeparator)。

inputSeparator: string (default: '__')

argvenv 存储引擎在加载值时使用此选项。 由于大多数系统只允许在环境变量和命令行参数中使用破折号、下划线和字母数字字符,因此 inputSeparator 提供了一种从这些来源加载分层值的机制。

disableDefaultAccessSeparator: {true|false} (default: false)

禁用 ':' 的默认访问分隔符,否则它始终可用。 这主要用于保留遗留行为。 它还可以用于设置包含默认分隔符的键(例如 { 'some:long:key' : 'some value' })。

Argv

负责将yargsprocess.argv解析出来的值加载到配置层次结构中。 有关选项格式的更多信息,请参阅 yargs 选项文档

Options

parseValues: {true|false} (default: false)

尝试解析众所周知的值(例如“false”、“true”、“null”、“undefined”、“3”、“5.1”和 JSON 值) 进入他们适当的类型。 如果一个值不能被解析,它将保持一个字符串。

transform: function(obj)

将每个键/值对传递给指定的函数进行转换。

输入 obj 包含以下列格式传递的两个属性:

{
  key: '<string>',
  value: '<string>'
}

转换函数可以同时更改键和值。

该函数可以返回与输入格式相同的对象或计算结果为 false 的值。 如果返回值为 false,则该条目将从存储中删除,否则它将替换原始键/值。

注意:如果返回值不遵守上述规则,将抛出异常。

Examples

  //
  // Can optionally also be an object literal to pass to `yargs`.
  //
  nconf.argv({
    "x": {
      alias: 'example',
      describe: 'Example description for usage generation',
      demand: true,
      default: 'some-value',
      parseValues: true,
      transform: function(obj) {
        if (obj.key === 'foo') {
          obj.value = 'baz';
        }
        return obj;
      }
    }
  });

也可以通过配置的 yargs 实例

  nconf.argv(require('yargs')
    .version('1.2.3')
    .usage('My usage definition')
    .strict()
    .options({
      "x": {
        alias: 'example',
        describe: 'Example description for usage generation',
        demand: true,
        default: 'some-value'
      }
    }));

Env

负责加载从 process.env 解析的值 进入配置层次结构。 默认情况下,env 变量值作为字符串加载到配置中。

Options

lowerCase: {true|false} (default: false)

将所有输入键转换为小写。 值未修改。

如果启用此选项,所有对 nconf.get() 的调用都必须传入小写字符串(例如 nconf.get('port')

parseValues: {true|false} (default: false)

尝试解析好-已知值(例如“假”、“真”、“空”、“未定义”、“3”、“5.1”和 JSON 值) 进入他们适当的类型。 如果一个值不能被解析,它将保持一个字符串。

transform: function(obj)

将每个键/值对传递给指定的函数进行转换。

输入 obj 包含以下列格式传递的两个属性:

{
  key: '<string>',
  value: '<string>'
}

转换函数可以同时更改键和值。

该函数可以返回与输入格式相同的对象或计算结果为 false 的值。 如果返回值为 false,则该条目将从存储中删除,否则它将替换原始键/值。

注意:如果返回值不符合上述规则,将抛出异常。

readOnly: {true|false} (default: true)

允许将来更新 env 存储中的值。 默认是不允许更新 env 存储中的项目。

Examples

  //
  // Can optionally also be an Array of values to limit process.env to.
  //
  nconf.env(['only', 'load', 'these', 'values', 'from', 'process.env']);

  //
  // Can also specify an input separator for nested keys
  //
  nconf.env('__');
  // Get the value of the env variable 'database__host'
  var dbHost = nconf.get('database:host');

  //
  // Can also lowerCase keys.
  // Especially handy when dealing with environment variables which are usually
  // uppercased while argv are lowercased.
  //

  // Given an environment variable PORT=3001
  nconf.env();
  var port = nconf.get('port') // undefined

  nconf.env({ lowerCase: true });
  var port = nconf.get('port') // 3001

  //
  // Or use all options
  //
  nconf.env({
    inputSeparator: '__',
    match: /^whatever_matches_this_will_be_whitelisted/
    whitelist: ['database__host', 'only', 'load', 'these', 'values', 'if', 'whatever_doesnt_match_but_is_whitelisted_gets_loaded_too'],
    lowerCase: true,
    parseValues: true,
    transform: function(obj) {
      if (obj.key === 'foo') {
        obj.value = 'baz';
      }
      return obj;
    }
  });
  var dbHost = nconf.get('database:host');

Literal

将给定的对象文字加载到配置层次结构中。 nconf.defaults()nconf.overrides() 都使用 Literal 存储。

  nconf.defaults({
    'some': 'default value'
  });

File

基于内存存储,但提供了额外的方法 .save().load() 允许您从文件读取配置。 与内存存储一样,所有方法调用都是同步的,但 .save().load() 除外,它们采用回调函数。

请务必注意,在调用 .save() 之前,文件引擎中的设置键不会持久保存到磁盘。 请注意,如果使用多个文件,则必须提供自定义键作为层次结构工作的第一个参数。

  nconf.file('path/to/your/config.json');
  // add multiple files, hierarchically. notice the unique key for each file
  nconf.file('user', 'path/to/your/user.json');
  nconf.file('global', 'path/to/your/global.json');

文件存储还可以扩展为多种文件格式,默认为 JSON。 要使用自定义格式,只需将格式对象传递给 .use() 方法即可。 该对象必须具有 .parse().stringify() 方法,就像本机 JSON 对象一样。

如果文件在提供的路径中不存在,则存储区将是空的。

Encrypting file contents

nconf@0.8.0 开始,现在可以使用 secure 选项加密和解密文件内容:

nconf.file('secure-file', {
  file: 'path/to/secure-file.json',
  secure: {
    secret: 'super-secretzzz-keyzz',
    alg: 'aes-256-ctr'
  }
})

这将使用 crypto.createCipheriv,默认为 aes-256-ctr。 加密的文件内容将如下所示:

{
  "config-key-name": {
    "alg": "aes-256-ctr", // cipher used
    "value": "af07fbcf",   // encrypted contents
    "iv": "49e7803a2a5ef98c7a51a8902b76dd10" // initialization vector
  },
  "another-config-key": {
    "alg": "aes-256-ctr",   // cipher used
    "value": "e310f6d94f13", // encrypted contents
    "iv": "b654e01aed262f37d0acf200be193985" // initialization vector
  },
}

Redis

通过 nconf-redis 可以使用一个单独的基于 Redis 的存储。 要简单地安装和使用此存储:

  $ npm install nconf
  $ npm install nconf-redis

一旦安装了 nconfnconf-redis,您必须要求两个模块都使用 Redis 存储:

  var nconf = require('nconf');

  //
  // Requiring `nconf-redis` will extend the `nconf`
  // module.
  //
  require('nconf-redis');

  nconf.use('redis', { host: 'localhost', port: 6379, ttl: 60 * 60 * 1000 });

Installation

  npm install nconf --save

Run Tests

测试是用誓言编写的,并提供完整的涵盖所有 API 和存储引擎。

  $ npm test

Author: Charlie Robbins

License: MIT

nconf

Version npmnpm DownloadsBuild StatusCoverageDependencies

Hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging.

Example

Using nconf is easy; it is designed to be a simple key-value store with support for both local and remote storage. Keys are namespaced and delimited by :. Let's dive right into sample usage:

  // sample.js
  var nconf = require('nconf');

  //
  // Setup nconf to use (in-order):
  //   1. Command-line arguments
  //   2. Environment variables
  //   3. A file located at 'path/to/config.json'
  //
  nconf.argv()
   .env()
   .file({ file: 'path/to/config.json' });

  //
  // Set a few variables on `nconf`.
  //
  nconf.set('database:host', '127.0.0.1');
  nconf.set('database:port', 5984);

  //
  // Get the entire database object from nconf. This will output
  // { host: '127.0.0.1', port: 5984 }
  //
  console.log('foo: ' + nconf.get('foo'));
  console.log('NODE_ENV: ' + nconf.get('NODE_ENV'));
  console.log('database: ' + nconf.get('database'));

  //
  // Save the configuration object to disk
  //
  nconf.save(function (err) {
    require('fs').readFile('path/to/your/config.json', function (err, data) {
      console.dir(JSON.parse(data.toString()))
    });
  });

If you run the below script:

  $ NODE_ENV=production node sample.js --foo bar

The output will be:

  foo: bar
  NODE_ENV: production
  database: { host: '127.0.0.1', port: 5984 }

Hierarchical configuration

Configuration management can get complicated very quickly for even trivial applications running in production. nconf addresses this problem by enabling you to setup a hierarchy for different sources of configuration with no defaults. The order in which you attach these configuration sources determines their priority in the hierarchy. Let's take a look at the options available to you

  1. nconf.argv(options) Loads process.argv using yargs. If options is supplied it is passed along to yargs.
  2. nconf.env(options) Loads process.env into the hierarchy.
  3. nconf.file(options) Loads the configuration data at options.file into the hierarchy.
  4. nconf.defaults(options) Loads the data in options.store into the hierarchy.
  5. nconf.overrides(options) Loads the data in options.store into the hierarchy.

A sane default for this could be:

  var nconf = require('nconf');

  //
  // 1. any overrides
  //
  nconf.overrides({
    'always': 'be this value'
  });

  //
  // 2. `process.env`
  // 3. `process.argv`
  //
  nconf.env().argv();

  //
  // 4. Values in `config.json`
  //
  nconf.file('/path/to/config.json');

  //
  // Or with a custom name
  // Note: A custom key must be supplied for hierarchy to work if multiple files are used.
  //
  nconf.file('custom', '/path/to/config.json');

  //
  // Or searching from a base directory.
  // Note: `name` is optional.
  //
  nconf.file(name, {
    file: 'config.json',
    dir: 'search/from/here',
    search: true
  });

  //
  // 5. Any default values
  //
  nconf.defaults({
    'if nothing else': 'use this value'
  });

API Documentation

The top-level of nconf is an instance of the nconf.Provider abstracts this all for you into a simple API.

nconf.add(name, options)

Adds a new store with the specified name and options. If options.type is not set, then name will be used instead:

  nconf.add('supplied', { type: 'literal', store: { 'some': 'config' } });
  nconf.add('user', { type: 'file', file: '/path/to/userconf.json' });
  nconf.add('global', { type: 'file', file: '/path/to/globalconf.json' });

nconf.any(names, callback)

Given a set of key names, gets the value of the first key found to be truthy. The key names can be given as separate arguments or as an array. If the last argument is a function, it will be called with the result; otherwise, the value is returned.

  //
  // Get one of 'NODEJS_PORT' and 'PORT' as a return value
  //
  var port = nconf.any('NODEJS_PORT', 'PORT');

  //
  // Get one of 'NODEJS_IP' and 'IPADDRESS' using a callback
  //
  nconf.any(['NODEJS_IP', 'IPADDRESS'], function(err, value) {
    console.log('Connect to IP address ' + value);
  });

nconf.use(name, options)

Similar to nconf.add, except that it can replace an existing store if new options are provided

  //
  // Load a file store onto nconf with the specified settings
  //
  nconf.use('file', { file: '/path/to/some/config-file.json' });

  //
  // Replace the file store with new settings
  //
  nconf.use('file', { file: 'path/to/a-new/config-file.json' });

nconf.remove(name)

Removes the store with the specified name. The configuration stored at that level will no longer be used for lookup(s).

  nconf.remove('file');

nconf.required(keys)

Declares a set of string keys to be mandatory, and throw an error if any are missing.

  nconf.defaults({
    keya: 'a',
  });

  nconf.required(['keya', 'keyb']);
  // Error: Missing required keys: keyb

You can also chain .required() calls when needed. for example when a configuration depends on another configuration store

config
  .argv()
  .env()
  .required([ 'STAGE']) //here you should have STAGE otherwise throw an error
  .file( 'stage', path.resolve( 'configs', 'stages', config.get( 'STAGE' ) + '.json' ) )
  .required([ 'OAUTH:redirectURL']) // here you should have OAUTH:redirectURL, otherwise throw an error
  .file( 'oauth', path.resolve( 'configs', 'oauth', config.get( 'OAUTH:MODE' ) + '.json' ) )
  .file( 'app', path.resolve( 'configs', 'app.json' ) )
  .required([ 'LOGS_MODE']) // here you should haveLOGS_MODE, otherwise throw an error
  .add( 'logs', {
    type: 'literal',
    store: require( path.resolve( 'configs', 'logs', config.get( 'LOGS_MODE' ) + '.js') )
  } )
  .defaults( defaults );

Storage Engines

Memory

A simple in-memory storage engine that stores a nested JSON representation of the configuration. To use this engine, just call .use() with the appropriate arguments. All calls to .get(), .set(), .clear(), .reset() methods are synchronous since we are only dealing with an in-memory object.

All built-in storage engines inherit from the Memory store.

Basic usage:

  nconf.use('memory');

Options

The options defined below apply to all storage engines that inherit from Memory.

accessSeparator: string (default: ':')

Defines the separator used to get or set data using the get() and set() methods. Even if this is changed, the default "colon" separator will be available unless explicitly disabled (see disableDefaultAccessSeparator).

inputSeparator: string (default: '__')

This option is used by the argv and env storage engines when loading values. Since most systems only allow dashes, underscores, and alphanumeric characters in environment variables and command line arguments, the inputSeparator provides a mechanism for loading hierarchical values from these sources.

disableDefaultAccessSeparator: {true|false} (default: false)

Disables the default access separator of ':', which is always available otherwise. This is mainly used to preserve legacy behavior. It can also be used to set keys that contain the default separator (e.g. { 'some:long:key' : 'some value' }).

Argv

Responsible for loading the values parsed from process.argv by yargs into the configuration hierarchy. See the yargs option docs for more on the option format.

Options

parseValues: {true|false} (default: false)

Attempt to parse well-known values (e.g. 'false', 'true', 'null', 'undefined', '3', '5.1' and JSON values) into their proper types. If a value cannot be parsed, it will remain a string.

transform: function(obj)

Pass each key/value pair to the specified function for transformation.

The input obj contains two properties passed in the following format:

{
  key: '<string>',
  value: '<string>'
}

The transformation function may alter both the key and the value.

The function may return either an object in the same format as the input or a value that evaluates to false. If the return value is falsey, the entry will be dropped from the store, otherwise it will replace the original key/value.

Note: If the return value doesn't adhere to the above rules, an exception will be thrown.

Examples

  //
  // Can optionally also be an object literal to pass to `yargs`.
  //
  nconf.argv({
    "x": {
      alias: 'example',
      describe: 'Example description for usage generation',
      demand: true,
      default: 'some-value',
      parseValues: true,
      transform: function(obj) {
        if (obj.key === 'foo') {
          obj.value = 'baz';
        }
        return obj;
      }
    }
  });

It's also possible to pass a configured yargs instance

  nconf.argv(require('yargs')
    .version('1.2.3')
    .usage('My usage definition')
    .strict()
    .options({
      "x": {
        alias: 'example',
        describe: 'Example description for usage generation',
        demand: true,
        default: 'some-value'
      }
    }));

Env

Responsible for loading the values parsed from process.env into the configuration hierarchy. By default, the env variables values are loaded into the configuration as strings.

Options

lowerCase: {true|false} (default: false)

Convert all input keys to lower case. Values are not modified.

If this option is enabled, all calls to nconf.get() must pass in a lowercase string (e.g. nconf.get('port'))

parseValues: {true|false} (default: false)

Attempt to parse well-known values (e.g. 'false', 'true', 'null', 'undefined', '3', '5.1' and JSON values) into their proper types. If a value cannot be parsed, it will remain a string.

transform: function(obj)

Pass each key/value pair to the specified function for transformation.

The input obj contains two properties passed in the following format:

{
  key: '<string>',
  value: '<string>'
}

The transformation function may alter both the key and the value.

The function may return either an object in the same format as the input or a value that evaluates to false. If the return value is falsey, the entry will be dropped from the store, otherwise it will replace the original key/value.

Note: If the return value doesn't adhere to the above rules, an exception will be thrown.

readOnly: {true|false} (default: true)

Allow values in the env store to be updated in the future. The default is to not allow items in the env store to be updated.

Examples

  //
  // Can optionally also be an Array of values to limit process.env to.
  //
  nconf.env(['only', 'load', 'these', 'values', 'from', 'process.env']);

  //
  // Can also specify an input separator for nested keys
  //
  nconf.env('__');
  // Get the value of the env variable 'database__host'
  var dbHost = nconf.get('database:host');

  //
  // Can also lowerCase keys.
  // Especially handy when dealing with environment variables which are usually
  // uppercased while argv are lowercased.
  //

  // Given an environment variable PORT=3001
  nconf.env();
  var port = nconf.get('port') // undefined

  nconf.env({ lowerCase: true });
  var port = nconf.get('port') // 3001

  //
  // Or use all options
  //
  nconf.env({
    inputSeparator: '__',
    match: /^whatever_matches_this_will_be_whitelisted/
    whitelist: ['database__host', 'only', 'load', 'these', 'values', 'if', 'whatever_doesnt_match_but_is_whitelisted_gets_loaded_too'],
    lowerCase: true,
    parseValues: true,
    transform: function(obj) {
      if (obj.key === 'foo') {
        obj.value = 'baz';
      }
      return obj;
    }
  });
  var dbHost = nconf.get('database:host');

Literal

Loads a given object literal into the configuration hierarchy. Both nconf.defaults() and nconf.overrides() use the Literal store.

  nconf.defaults({
    'some': 'default value'
  });

File

Based on the Memory store, but provides additional methods .save() and .load() which allow you to read your configuration to and from file. As with the Memory store, all method calls are synchronous with the exception of .save() and .load() which take callback functions.

It is important to note that setting keys in the File engine will not be persisted to disk until a call to .save() is made. Note a custom key must be supplied as the first parameter for hierarchy to work if multiple files are used.

  nconf.file('path/to/your/config.json');
  // add multiple files, hierarchically. notice the unique key for each file
  nconf.file('user', 'path/to/your/user.json');
  nconf.file('global', 'path/to/your/global.json');

The file store is also extensible for multiple file formats, defaulting to JSON. To use a custom format, simply pass a format object to the .use() method. This object must have .parse() and .stringify() methods just like the native JSON object.

If the file does not exist at the provided path, the store will simply be empty.

Encrypting file contents

As of nconf@0.8.0 it is now possible to encrypt and decrypt file contents using the secure option:

nconf.file('secure-file', {
  file: 'path/to/secure-file.json',
  secure: {
    secret: 'super-secretzzz-keyzz',
    alg: 'aes-256-ctr'
  }
})

This will encrypt each key using crypto.createCipheriv, defaulting to aes-256-ctr. The encrypted file contents will look like this:

{
  "config-key-name": {
    "alg": "aes-256-ctr", // cipher used
    "value": "af07fbcf",   // encrypted contents
    "iv": "49e7803a2a5ef98c7a51a8902b76dd10" // initialization vector
  },
  "another-config-key": {
    "alg": "aes-256-ctr",   // cipher used
    "value": "e310f6d94f13", // encrypted contents
    "iv": "b654e01aed262f37d0acf200be193985" // initialization vector
  },
}

Redis

There is a separate Redis-based store available through nconf-redis. To install and use this store simply:

  $ npm install nconf
  $ npm install nconf-redis

Once installing both nconf and nconf-redis, you must require both modules to use the Redis store:

  var nconf = require('nconf');

  //
  // Requiring `nconf-redis` will extend the `nconf`
  // module.
  //
  require('nconf-redis');

  nconf.use('redis', { host: 'localhost', port: 6379, ttl: 60 * 60 * 1000 });

Installation

  npm install nconf --save

Run Tests

Tests are written in vows and give complete coverage of all APIs and storage engines.

  $ npm test

Author: Charlie Robbins

License: MIT

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文