or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

argv-env.mdconfiguration.mdfiles.mdindex.mdstores.mdutilities.md

argv-env.mddocs/

0

# Command Line and Environment

1

2

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.

3

4

## Capabilities

5

6

### Command Line Arguments

7

8

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

9

10

```javascript { .api }

11

/**

12

* Add command-line arguments store to hierarchy

13

* @param {Object|Function} [options] - yargs options object or yargs instance

14

* @returns {Provider} Provider instance for chaining

15

*/

16

argv(options);

17

```

18

19

**Usage Examples:**

20

21

```javascript

22

const nconf = require('nconf');

23

24

// Basic argv parsing

25

nconf.argv();

26

27

// With yargs options

28

nconf.argv({

29

'port': {

30

'alias': 'p',

31

'describe': 'Server port',

32

'default': 3000,

33

'type': 'number'

34

},

35

'env': {

36

'alias': 'e',

37

'describe': 'Environment',

38

'choices': ['development', 'production', 'test']

39

},

40

'verbose': {

41

'alias': 'v',

42

'describe': 'Verbose logging',

43

'type': 'boolean'

44

}

45

});

46

47

// With value parsing

48

nconf.argv({

49

parseValues: true, // Parse string values to native types

50

separator: '__' // Use __ for nested keys: --db__host=localhost

51

});

52

53

// With transformation

54

nconf.argv({

55

transform: function(obj) {

56

// Transform each key-value pair

57

return {

58

key: obj.key.toUpperCase(),

59

value: obj.value

60

};

61

}

62

});

63

64

// Usage: node app.js --port 8080 --env production --verbose

65

// Results in: { port: 8080, env: 'production', verbose: true }

66

```

67

68

### Environment Variables

69

70

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

71

72

```javascript { .api }

73

/**

74

* Add environment variables store to hierarchy

75

* @param {Object|Array|string|RegExp} [options] - Environment options, whitelist array, or separator

76

* @returns {Provider} Provider instance for chaining

77

*/

78

env(options);

79

```

80

81

**Usage Examples:**

82

83

```javascript

84

// Basic environment variables

85

nconf.env();

86

87

// With separator for nested keys

88

nconf.env('__'); // DB__HOST becomes { DB: { HOST: value } }

89

90

// With whitelist array

91

nconf.env(['NODE_ENV', 'PORT', 'DATABASE_URL']);

92

93

// With full options

94

nconf.env({

95

separator: '__',

96

whitelist: ['NODE_ENV', 'PORT', 'DB_HOST', 'DB_PORT'],

97

lowerCase: true, // Convert keys to lowercase

98

parseValues: true // Parse values to native types

99

});

100

101

// With regex matching

102

nconf.env({

103

match: /^MYAPP_/, // Only variables starting with MYAPP_

104

transform: function(obj) {

105

// Remove prefix and convert to lowercase

106

return {

107

key: obj.key.replace(/^MYAPP_/, '').toLowerCase(),

108

value: obj.value

109

};

110

}

111

});

112

113

// With prefix filtering

114

nconf.env({

115

prefix: 'MYAPP_', // Only load variables with this prefix

116

lowerCase: true

117

});

118

```

119

120

## Advanced Argv Features

121

122

### Yargs Integration

123

124

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

125

126

```javascript { .api }

127

/**

128

* Argv store properties available after loading

129

*/

130

interface ArgvStore {

131

showHelp: Function; // yargs.showHelp function

132

help: Function; // yargs.help function

133

}

134

```

135

136

**Usage Examples:**

137

138

```javascript

139

// Complex yargs configuration

140

nconf.argv({

141

'config': {

142

'alias': 'c',

143

'describe': 'Configuration file path',

144

'type': 'string',

145

'demandOption': true

146

},

147

'database-host': {

148

'describe': 'Database hostname',

149

'type': 'string',

150

'default': 'localhost'

151

},

152

'workers': {

153

'alias': 'w',

154

'describe': 'Number of worker processes',

155

'type': 'number',

156

'default': require('os').cpus().length

157

}

158

}, 'Usage: $0 --config <file> [options]');

159

160

// Access yargs help

161

const argvStore = nconf.stores.argv;

162

if (nconf.get('help')) {

163

argvStore.showHelp();

164

process.exit(0);

165

}

166

167

// Nested argument parsing

168

nconf.argv({

169

separator: '-', // --database-host-primary becomes database:host:primary

170

parseValues: true

171

});

172

```

173

174

### Value Transformation

175

176

Transform command-line arguments and environment variables during loading.

177

178

```javascript { .api }

179

/**

180

* Transformation function for key-value pairs

181

* @param {Object} obj - Object with key and value properties

182

* @param {string} obj.key - The configuration key

183

* @param {*} obj.value - The configuration value

184

* @returns {Object|null} Transformed object or null to skip

185

*/

186

function transform(obj);

187

```

188

189

**Usage Examples:**

190

191

```javascript

192

// Environment variable transformation

193

nconf.env({

194

transform: function(obj) {

195

// Convert SCREAMING_SNAKE_CASE to kebab-case

196

const key = obj.key.toLowerCase().replace(/_/g, '-');

197

return { key: key, value: obj.value };

198

}

199

});

200

201

// Argv transformation with validation

202

nconf.argv({

203

transform: function(obj) {

204

// Skip help and version flags

205

if (['help', 'version', 'h', 'v'].includes(obj.key)) {

206

return null;

207

}

208

209

// Convert boolean strings

210

if (obj.value === 'true') obj.value = true;

211

if (obj.value === 'false') obj.value = false;

212

213

return obj;

214

}

215

});

216

217

// Complex transformation for nested configuration

218

nconf.env({

219

separator: '__',

220

transform: function(obj) {

221

// APP__DATABASE__HOST -> app:database:host

222

if (obj.key.startsWith('APP__')) {

223

return {

224

key: obj.key.replace(/^APP__/, '').toLowerCase().replace(/__/g, ':'),

225

value: obj.value

226

};

227

}

228

return null; // Skip non-APP variables

229

}

230

});

231

```

232

233

## Environment Variable Features

234

235

### Filtering and Whitelisting

236

237

Control which environment variables are loaded with multiple filtering mechanisms.

238

239

```javascript { .api }

240

/**

241

* Environment filtering options

242

*/

243

interface EnvFilterOptions {

244

whitelist?: string[]; // Array of allowed variable names

245

match?: RegExp; // Regex pattern to match variable names

246

prefix?: string; // Variable name prefix filter

247

}

248

```

249

250

**Usage Examples:**

251

252

```javascript

253

// Whitelist specific variables

254

nconf.env({

255

whitelist: [

256

'NODE_ENV',

257

'PORT',

258

'DATABASE_URL',

259

'JWT_SECRET',

260

'REDIS_URL'

261

]

262

});

263

264

// Regex pattern matching

265

nconf.env({

266

match: /^(NODE_|DB_|API_)/, // Variables starting with NODE_, DB_, or API_

267

lowerCase: true

268

});

269

270

// Prefix with whitelist combination

271

nconf.env({

272

prefix: 'MYAPP_',

273

whitelist: ['MYAPP_DEBUG', 'MYAPP_PORT'], // Both conditions must match

274

transform: function(obj) {

275

// Remove prefix after filtering

276

return {

277

key: obj.key.replace(/^MYAPP_/, '').toLowerCase(),

278

value: obj.value

279

};

280

}

281

});

282

283

// Case sensitivity handling

284

nconf.env({

285

lowerCase: true, // Convert all keys to lowercase

286

separator: '_', // NODE_ENV becomes node:env

287

parseValues: true // "true" -> true, "123" -> 123

288

});

289

```

290

291

### Nested Key Creation

292

293

Create nested configuration objects from delimited environment variable names.

294

295

**Usage Examples:**

296

297

```javascript

298

// Environment variables:

299

// DB_HOST=localhost

300

// DB_PORT=5432

301

// DB_POOL_MIN=2

302

// DB_POOL_MAX=10

303

304

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

305

306

// Results in nested structure:

307

// {

308

// DB: {

309

// HOST: 'localhost',

310

// PORT: '5432',

311

// POOL: {

312

// MIN: '2',

313

// MAX: '10'

314

// }

315

// }

316

// }

317

318

// With parsing and case conversion:

319

nconf.env({

320

separator: '_',

321

lowerCase: true,

322

parseValues: true

323

});

324

325

// Results in:

326

// {

327

// db: {

328

// host: 'localhost',

329

// port: 5432,

330

// pool: {

331

// min: 2,

332

// max: 10

333

// }

334

// }

335

// }

336

```

337

338

### Value Parsing

339

340

Automatic conversion of string values to native JavaScript types.

341

342

```javascript { .api }

343

/**

344

* Parse string values to native types

345

* @param {string} value - String value to parse

346

* @returns {*} Parsed value (boolean, number, object, array, or string)

347

*/

348

parseValues(value);

349

```

350

351

**Usage Examples:**

352

353

```javascript

354

// Environment variables with string values:

355

// DEBUG=true

356

// MAX_CONNECTIONS=100

357

// CONFIG={"timeout":5000}

358

// FEATURES=["auth","logging"]

359

// UNDEFINED_VAL=undefined

360

361

nconf.env({ parseValues: true });

362

363

// Parsed results:

364

// {

365

// DEBUG: true, // boolean

366

// MAX_CONNECTIONS: 100, // number

367

// CONFIG: {timeout: 5000}, // object

368

// FEATURES: ["auth","logging"], // array

369

// UNDEFINED_VAL: undefined // undefined

370

// }

371

372

// Combined with argv parsing

373

nconf

374

.argv({ parseValues: true })

375

.env({ parseValues: true });

376

377

// Command: node app.js --debug=false --port=8080

378

// Environment: DEBUG=true PORT=3000

379

// Result: { debug: false, port: 8080 } (argv takes precedence)

380

```

381

382

## Usage Patterns

383

384

### Common Configuration Hierarchy

385

386

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

387

388

```javascript

389

const nconf = require('nconf');

390

391

// Setup configuration hierarchy (order = priority)

392

nconf

393

// 1. Command-line arguments (highest priority)

394

.argv({

395

'config': {

396

'alias': 'c',

397

'describe': 'Configuration file path',

398

'type': 'string'

399

},

400

'env': {

401

'alias': 'e',

402

'describe': 'Environment name',

403

'type': 'string'

404

}

405

})

406

407

// 2. Environment variables

408

.env({

409

separator: '__',

410

parseValues: true,

411

whitelist: [

412

'NODE_ENV',

413

'PORT',

414

'DATABASE__HOST',

415

'DATABASE__PORT',

416

'JWT__SECRET'

417

]

418

})

419

420

// 3. Configuration file

421

.file({

422

file: nconf.get('config') || './config.json'

423

});

424

425

// Usage examples:

426

// node app.js --env production --port 8080

427

// NODE_ENV=development DATABASE__HOST=localhost node app.js

428

// node app.js --config ./prod.json

429

```

430

431

### Application Startup Pattern

432

433

Complete application configuration setup with validation and error handling.

434

435

```javascript

436

const nconf = require('nconf');

437

438

function initializeConfig() {

439

// Setup configuration sources

440

nconf

441

.argv()

442

.env({

443

separator: '__',

444

parseValues: true

445

})

446

.file('./config.json')

447

.defaults({

448

port: 3000,

449

env: 'development',

450

database: {

451

host: 'localhost',

452

port: 5432

453

}

454

});

455

456

// Validate required configuration

457

try {

458

nconf.required(['database:host', 'database:port']);

459

} catch (err) {

460

console.error('Missing required configuration:', err.message);

461

process.exit(1);

462

}

463

464

// Log configuration (excluding secrets)

465

const config = nconf.get();

466

const sanitized = { ...config };

467

delete sanitized.jwt_secret;

468

delete sanitized.database?.password;

469

470

console.log('Configuration loaded:', sanitized);

471

return config;

472

}

473

474

module.exports = initializeConfig;

475

```