javascriptnode.jstypescriptnode-commander

commander.js simple use case: one single file argument


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:


Solution

  • 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);