Search code examples
node.jsnconf

Capturing command line arguments using NCONF


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?


Solution

  • 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