-
Couldn't load subscription status.
- Fork 258
Description
Forgive me if this is a silly question, but after a few hours reading the docs for nconf and yargs I've not been able to figure it out. Say I have this program that reads config from argv or env, and it normalises the parameter names from each source using transform() functions:
const nconf = require('nconf')
const yargs = require('yargs')
const ENV_PREFIX = /^DEMO_/
nconf.argv({
transform ({ key, value }) {
key = key.replace(/-/g, '_')
return { key, value }
},
parseValues: true
})
nconf.env({
transform ({ key, value }) {
if (ENV_PREFIX.test(key)) {
key = key.replace(ENV_PREFIX, '').toLowerCase()
return { key, value }
}
},
parseValues: true
})
let options = {
setup: nconf.get('setup'),
max_jobs: nconf.get('max_jobs')
}
console.log(options)This parses values from each source correctly and selects values with the correct precedence:
$ node nconf-demo.js
{ setup: undefined, max_jobs: undefined }
$ DEMO_SETUP=true DEMO_MAX_JOBS=2 node nconf-demo.js
{ setup: true, max_jobs: 2 }
$ DEMO_SETUP=true DEMO_MAX_JOBS=2 node nconf-demo.js --no-setup --max-jobs 3
{ setup: false, max_jobs: 3 }
However, certain argument names cause special behaviour in yargs, for example if you use --help or --version then yargs executes a special handler and terminates the process:
$ node nconf-demo.js --help
Options:
--help Show help [boolean]
--version Show version number [boolean]
Allowing the config parser to exit the process is not desirable behaviour for a long-running process, and it also makes the application impossible to test other than by bypassing its CLI script, so I would like to turn this behaviour off. I tried doing this by modifying the argv() call as follows:
nconf.argv(yargs.help(false).version(false), {
transform ({ key, value }) {
key = key.replace(/-/g, '_')
return { key, value }
},
parseValues: true
})This causes strange behaviour, for example the --max-job setting is ignored:
$ DEMO_SETUP=true DEMO_MAX_JOBS=2 node nconf-demo.js --no-setup --max-jobs 3
{ setup: false, max_jobs: 2 }
It turns out that in this case, the transform() function for argv is not executed, so the key remains as max-jobs instead of being canonicalised to max_jobs.
Is it possible to turn off these special behaviours of yargs so that it functions only as an argument parser, without printing its own output or exiting the process, while using nconf options like transform() at the same time?
As an aside, I discovered that parseValues is also ignored here, but its default value for argv is true contrary to what the docs say. i.e. calling nconf.argv({ parseValues: false }) has no effect; arguments are turned into numbers and booleans rather than remaining as strings.