Node.js commander: default for variadic option?

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");
    .option("-e, --extensions <ext...>", "file extensions to load", "dat")
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 answers

  • answered 2022-04-12 23:51 shadowspawn

    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"]);

  • answered 2022-04-14 06:56 SiliconValley

    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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum