2

I've seen that most people use commander npm package when having to deal with command-line parsing. I would like to use it as well because it seems to have pretty advanced functionality (e.g. commands, help, option flags, etc).

However, for the first version of my program I don't need such advanced features, I just need commander to parse the arguments, and find a single filename provided (mandatory argument).

I've tried:

import commander = require("commander");

const cli =
  commander
    .version("1.0.0")
    .description("Foo bar baz")
    .usage('[options] <file>')
    .arguments('<file>')
    .action(function(file) {
        if (file == null) console.log("no file")
        else console.log("file was " + file);
    })
    .parse(process.argv);

However, with this:

  • Nothing gets printed if I don't pass any argument, am I using the action() function properly or is my null check wrong? Ideally it should print the usage string I pass in this case, and finish with exitCode!=0?
  • How can I detect if the user sent too many filenames (too many arguments) and give her an error?
knocte
  • 16,941
  • 11
  • 79
  • 125

1 Answers1

3

It seems that action function won't be executed when no argument based on issue.

But you can check like

const cli = commander
    .version('0.1.0')
    .usage('[options] <file>')
    .arguments('<file>')
    .action(function(file) {
        fileValue = file;
    })
    .parse(process.argv);

if (typeof fileValue === 'undefined') {
    console.error('no file given!');
    process.exit(1);
}
console.log('file was ' + fileValue);
iMavis
  • 46
  • 2
  • you can check extra arguments by removing the 1st (node command), the 2nd (js name) and the third (file name) by ```if (process.argv.slice(2+1).length > 0) console.error('more argv than needed!'); ``` – iMavis Apr 26 '18 at 13:36