Skip to content

How can I ensure that exactly one argument has been supplied? #1000

@roxspring

Description

@roxspring

I've tried defining a command with a single required argument, and attempted to validate that exactly one source specified:

import * as program from 'commander';
import { version } from 'pjson';

program
  .version(version)
  .arguments('<source.md>')
  .action((source: string): void => {
    console.log('source=' + source);
    program.source = source;
  })
  .parse(process.argv);

console.log(program.args);
console.log(program.args.length);

if (program.args.length !== 1) {
  console.log('Invalid arguments');
  program.help();
}

console.log(program.source);

And running the program with no arguments, correctly prints 'Invalid arguments' since program.args.length is 0. But with 1 argument (program a) program.args.length is 2!? and outputs the following, claiming that program.args.length is 2!?

source=a
[
  'a',
  Command {
    ...
  }
]
2
Invalid arguments

Weirdly running with four arguments program a b c d also appears to drop the b argument somehow:

source=a
[
  'a',
  Command {
    ...
  },
  'c',
  'd'
]
4
Invalid arguments

So I guess I have two questions:

  1. Where's the second argument gone?
  2. (more importantly) how can I ensure that exactly one argument has been supplied?

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions