CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nconf

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

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

argv-env.mddocs/

Command Line and Environment

Integration with command-line arguments via yargs and environment variables with filtering, transformation, and parsing capabilities. These stores provide read-only access to external configuration sources.

Capabilities

Command Line Arguments

Parse and integrate command-line arguments using yargs with support for complex option definitions and automatic help generation.

/**
 * Add command-line arguments store to hierarchy
 * @param {Object|Function} [options] - yargs options object or yargs instance
 * @returns {Provider} Provider instance for chaining
 */
argv(options);

Usage Examples:

const nconf = require('nconf');

// Basic argv parsing
nconf.argv();

// With yargs options
nconf.argv({
  'port': {
    'alias': 'p',
    'describe': 'Server port',
    'default': 3000,
    'type': 'number'
  },
  'env': {
    'alias': 'e', 
    'describe': 'Environment',
    'choices': ['development', 'production', 'test']
  },
  'verbose': {
    'alias': 'v',
    'describe': 'Verbose logging',
    'type': 'boolean'
  }
});

// With value parsing
nconf.argv({
  parseValues: true,  // Parse string values to native types
  separator: '__'     // Use __ for nested keys: --db__host=localhost
});

// With transformation
nconf.argv({
  transform: function(obj) {
    // Transform each key-value pair
    return {
      key: obj.key.toUpperCase(),
      value: obj.value
    };
  }
});

// Usage: node app.js --port 8080 --env production --verbose
// Results in: { port: 8080, env: 'production', verbose: true }

Environment Variables

Load and filter environment variables with support for whitelisting, transformation, and nested key creation.

/**
 * Add environment variables store to hierarchy
 * @param {Object|Array|string|RegExp} [options] - Environment options, whitelist array, or separator
 * @returns {Provider} Provider instance for chaining
 */
env(options);

Usage Examples:

// Basic environment variables
nconf.env();

// With separator for nested keys
nconf.env('__');  // DB__HOST becomes { DB: { HOST: value } }

// With whitelist array
nconf.env(['NODE_ENV', 'PORT', 'DATABASE_URL']);

// With full options
nconf.env({
  separator: '__',
  whitelist: ['NODE_ENV', 'PORT', 'DB_HOST', 'DB_PORT'],
  lowerCase: true,      // Convert keys to lowercase
  parseValues: true     // Parse values to native types
});

// With regex matching
nconf.env({
  match: /^MYAPP_/,     // Only variables starting with MYAPP_
  transform: function(obj) {
    // Remove prefix and convert to lowercase
    return {
      key: obj.key.replace(/^MYAPP_/, '').toLowerCase(),
      value: obj.value
    };
  }
});

// With prefix filtering
nconf.env({
  prefix: 'MYAPP_',     // Only load variables with this prefix
  lowerCase: true
});

Advanced Argv Features

Yargs Integration

Full integration with yargs for complex command-line argument processing.

/**
 * Argv store properties available after loading
 */
interface ArgvStore {
  showHelp: Function;   // yargs.showHelp function
  help: Function;       // yargs.help function
}

Usage Examples:

// Complex yargs configuration
nconf.argv({
  'config': {
    'alias': 'c',
    'describe': 'Configuration file path',
    'type': 'string',
    'demandOption': true
  },
  'database-host': {
    'describe': 'Database hostname',
    'type': 'string',
    'default': 'localhost'
  },
  'workers': {
    'alias': 'w',
    'describe': 'Number of worker processes',
    'type': 'number',
    'default': require('os').cpus().length
  }
}, 'Usage: $0 --config <file> [options]');

// Access yargs help
const argvStore = nconf.stores.argv;
if (nconf.get('help')) {
  argvStore.showHelp();
  process.exit(0);
}

// Nested argument parsing
nconf.argv({
  separator: '-',  // --database-host-primary becomes database:host:primary
  parseValues: true
});

Value Transformation

Transform command-line arguments and environment variables during loading.

/**
 * Transformation function for key-value pairs
 * @param {Object} obj - Object with key and value properties
 * @param {string} obj.key - The configuration key
 * @param {*} obj.value - The configuration value
 * @returns {Object|null} Transformed object or null to skip
 */
function transform(obj);

Usage Examples:

// Environment variable transformation
nconf.env({
  transform: function(obj) {
    // Convert SCREAMING_SNAKE_CASE to kebab-case
    const key = obj.key.toLowerCase().replace(/_/g, '-');
    return { key: key, value: obj.value };
  }
});

// Argv transformation with validation
nconf.argv({
  transform: function(obj) {
    // Skip help and version flags
    if (['help', 'version', 'h', 'v'].includes(obj.key)) {
      return null;
    }
    
    // Convert boolean strings
    if (obj.value === 'true') obj.value = true;
    if (obj.value === 'false') obj.value = false;
    
    return obj;
  }
});

// Complex transformation for nested configuration
nconf.env({
  separator: '__',
  transform: function(obj) {
    // APP__DATABASE__HOST -> app:database:host
    if (obj.key.startsWith('APP__')) {
      return {
        key: obj.key.replace(/^APP__/, '').toLowerCase().replace(/__/g, ':'),
        value: obj.value
      };
    }
    return null;  // Skip non-APP variables
  }
});

Environment Variable Features

Filtering and Whitelisting

Control which environment variables are loaded with multiple filtering mechanisms.

/**
 * Environment filtering options
 */
interface EnvFilterOptions {
  whitelist?: string[];      // Array of allowed variable names
  match?: RegExp;           // Regex pattern to match variable names
  prefix?: string;          // Variable name prefix filter
}

Usage Examples:

// Whitelist specific variables
nconf.env({
  whitelist: [
    'NODE_ENV',
    'PORT', 
    'DATABASE_URL',
    'JWT_SECRET',
    'REDIS_URL'
  ]
});

// Regex pattern matching
nconf.env({
  match: /^(NODE_|DB_|API_)/,  // Variables starting with NODE_, DB_, or API_
  lowerCase: true
});

// Prefix with whitelist combination
nconf.env({
  prefix: 'MYAPP_',
  whitelist: ['MYAPP_DEBUG', 'MYAPP_PORT'],  // Both conditions must match
  transform: function(obj) {
    // Remove prefix after filtering
    return {
      key: obj.key.replace(/^MYAPP_/, '').toLowerCase(),
      value: obj.value
    };
  }
});

// Case sensitivity handling
nconf.env({
  lowerCase: true,    // Convert all keys to lowercase
  separator: '_',     // NODE_ENV becomes node:env
  parseValues: true   // "true" -> true, "123" -> 123
});

Nested Key Creation

Create nested configuration objects from delimited environment variable names.

Usage Examples:

// Environment variables:
// DB_HOST=localhost
// DB_PORT=5432
// DB_POOL_MIN=2
// DB_POOL_MAX=10

nconf.env({ separator: '_' });

// Results in nested structure:
// {
//   DB: {
//     HOST: 'localhost',
//     PORT: '5432',
//     POOL: {
//       MIN: '2',
//       MAX: '10'
//     }
//   }
// }

// With parsing and case conversion:
nconf.env({
  separator: '_',
  lowerCase: true,
  parseValues: true
});

// Results in:
// {
//   db: {
//     host: 'localhost',
//     port: 5432,
//     pool: {
//       min: 2,
//       max: 10
//     }
//   }
// }

Value Parsing

Automatic conversion of string values to native JavaScript types.

/**
 * Parse string values to native types
 * @param {string} value - String value to parse
 * @returns {*} Parsed value (boolean, number, object, array, or string)
 */
parseValues(value);

Usage Examples:

// Environment variables with string values:
// DEBUG=true
// MAX_CONNECTIONS=100
// CONFIG={"timeout":5000}
// FEATURES=["auth","logging"]
// UNDEFINED_VAL=undefined

nconf.env({ parseValues: true });

// Parsed results:
// {
//   DEBUG: true,              // boolean
//   MAX_CONNECTIONS: 100,     // number  
//   CONFIG: {timeout: 5000},  // object
//   FEATURES: ["auth","logging"], // array
//   UNDEFINED_VAL: undefined  // undefined
// }

// Combined with argv parsing
nconf
  .argv({ parseValues: true })
  .env({ parseValues: true });

// Command: node app.js --debug=false --port=8080
// Environment: DEBUG=true PORT=3000
// Result: { debug: false, port: 8080 } (argv takes precedence)

Usage Patterns

Common Configuration Hierarchy

Typical setup combining command-line arguments, environment variables, and file configuration.

const nconf = require('nconf');

// Setup configuration hierarchy (order = priority)
nconf
  // 1. Command-line arguments (highest priority)
  .argv({
    'config': {
      'alias': 'c',
      'describe': 'Configuration file path',
      'type': 'string'
    },
    'env': {
      'alias': 'e',
      'describe': 'Environment name',
      'type': 'string'
    }
  })
  
  // 2. Environment variables
  .env({
    separator: '__',
    parseValues: true,
    whitelist: [
      'NODE_ENV',
      'PORT',
      'DATABASE__HOST',
      'DATABASE__PORT',
      'JWT__SECRET'
    ]
  })
  
  // 3. Configuration file
  .file({
    file: nconf.get('config') || './config.json'
  });

// Usage examples:
// node app.js --env production --port 8080
// NODE_ENV=development DATABASE__HOST=localhost node app.js
// node app.js --config ./prod.json

Application Startup Pattern

Complete application configuration setup with validation and error handling.

const nconf = require('nconf');

function initializeConfig() {
  // Setup configuration sources
  nconf
    .argv()
    .env({
      separator: '__',
      parseValues: true
    })
    .file('./config.json')
    .defaults({
      port: 3000,
      env: 'development',
      database: {
        host: 'localhost',
        port: 5432
      }
    });

  // Validate required configuration
  try {
    nconf.required(['database:host', 'database:port']);
  } catch (err) {
    console.error('Missing required configuration:', err.message);
    process.exit(1);
  }

  // Log configuration (excluding secrets)
  const config = nconf.get();
  const sanitized = { ...config };
  delete sanitized.jwt_secret;
  delete sanitized.database?.password;
  
  console.log('Configuration loaded:', sanitized);
  return config;
}

module.exports = initializeConfig;

docs

argv-env.md

configuration.md

files.md

index.md

stores.md

utilities.md

tile.json