I have written an utility that can be called via CLI, with arguments and flags. Unfortunately, for a reason that I ignore, commander.js does not parse the arguments properly. What am I missing?
Here's the commander.js setup script:
import { Command, Option } from "commander";
function parseArguments() {
const program = new Command();
program
.name('video-recorder')
.description('Video recorder utility capturing screen & sound output')
program.command("list-devices").description("Lists devices");
program
.command("capture")
.addOption(
new Option("-p --profile <profile>", "Profile to use to record")
.default(undefined),
)
.addOption(
new Option(
"-d --duration <time>",
"Duration of the video, in format [HH:]mm:ss",
)
)
.argument("<url>", "url to the page of the video")
.argument("<path>", "path to output to");
program.parse(process.argv);
return program;
}
async function main() {
const program = parseArguments();
const [url, outpath] = program.args;
const args = {
url: url,
outpath: outpath,
... program.opts(),
};
console.log(args)
// ...
}
main();
When calling said script using
node src/main.js capture -p abc -d '9:48' 'https://www.example.com/video-id' '/path/to/output_file.mp4'
I get the following args dictionary printed:
{ url: 'capture', outpath: '-p' }
Which is incorrect. It seems like commander.js skipped the name of the command, and put the arguments first instead of parsing the options provided.
How can I modify my script such that:
Any help would be greatly appreciated! Thanks!
If you have a subcommand like capture
, add an action handler to the subcommand using .action()
.
The action handler is passed the parsed arguments and options.