Node.js commander: default for variadic option?

215 views Asked by At

I want to have a variadic option with defaults, but I could enter only one value as default like this:

const program = new Command("ingest");
program
    .option("-e, --extensions <ext...>", "file extensions to load", "dat")
    .parse(process.argv);
const options = program.opts();

This works and the default is "dat". But what should I do if the default is an array of multiple strings like ["dat", "txt"]?

The first solution that I found is to not put a default and then, if options.extensions is undefined, load it with the default array. This works but obviously the default does not appear in the help.

The second solution that solves this small problem is to enter the default as a space separated string:

program.option("-e, --extensions <ext...>", "file extensions to load", "dat txt");

and then:

if(typeof options.extensions === "string")
    options.extensions = options.extensions.split(" ")

This way options.extensions is always an array of strings.

Could .addOption(new Option()) help here? Unfortunately I cannot find documentation for the Option class besides the three examples provided.

Thanks! mario

2

There are 2 answers

6
shadowspawn On BEST ANSWER

The default does not have to be a string. Use the array, and it might even simplify your later code since the option value will always be an array.

program.option("-e, --extensions <ext...>", "file extensions to load", ["dat", "txt"]);

TypeScript updated to include string[] in allowed types in Commander v9.3.0.

0
SiliconValley On

The most Typescript-friendly way to add an array default to a variadic option I have found is:

program.addOption(new Option("-e, --extensions <ext...>",
                             "file extensions to load").default(["dat", "txt"])

Hope it helps