I have a simple node.js backend script and I want to capture command line arguments along with the keys/values from a config.json file and environment variables. The second two I am having no problem with, but I am having nearly inexplicable trouble capturing the command line args.
I can capture the command line arguments this way:
var nconf = require('nconf');
nconf.argv().env().file({file: './config.json'});
var csvFilePath = nconf.argv().get()._[0]; // var csvFilePath = process.argv[2];
var csvType = nconf.argv().get()._[1]; // var csvType = process.argv[3];
these two calls are equivalent to process.argv[index], except the index is changed.
There has to be a more straightforward way to capture the command line arguments but even when I debug and look through the variables that nconf yields, I still can't figure it out.
Anyone with nconf experience care to help?
To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.
In Node. js, as in C and many related environments, all command-line arguments received by the shell are given to the process in an array called argv (short for 'argument values'). There you have it - an array containing any arguments you passed in.
I believe the best way to do this is like so:
//contents of app.js
var nconf = require('nconf').argv();
if you call your program with the follow command line command:
node app.js --one foo --two bar
then in your program you can access these command line args like so:
var nconf = require('nconf').argv();
var one = nconf.get('one'); //one = 'foo'
var two = nconf.get('two'); //two = 'bar'
so you need the -- symbol in front of the identifier, then you can access the command line args.
Frankly, as a message to the nconf module author Charlie Robbins, I think it would better to not mix everything into one big hash.
It would be better if you did this instead:
var foo = nconf.argv.get('one');
var node_env = nconf.env.get('NODE_ENV');
I think it is more intuitive and less error prone.
Also, for those starting node with 'npm start':
to my knowledge you need two extra hyphens like so:
npm start -- --one foo --two bar
with the extra hyphens/dashes you let Bash know that the args are for your node.js executable, not for the NPM node.js executable
Slightly shorter/cleaner:
var nconf = require('nconf');
nconf.argv().env().file({file: './config.json'});
var csvFilePath = nconf.get('_')[0]; // var csvFilePath = process.argv[2];
var csvType = nconf.get('_')[1]; // var csvType = process.argv[3];
If you name your parameter (say, --foo=bar
or -f bar
), then you can use .get('foo')
or .get('f')
rather than using the array index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With