loading...

re: Creating a CLI for your Node.js app using Typescript VIEW POST

FULL DISCUSSION
 

First of all, thanks for your sharing.

I've tested check() and I'd suggest approach 2. Here's the detail. Cheers.

Approach 1 prints out the validation result like the following:

  .check(data => {
      return !isNaN(data.port);
  })

ts-node src/index.ts -e dev -p abc
Options:
  --help      Show help                                                [boolean]
  --version   Show version number                                      [boolean]
  --env, -e   app environment                [required] [choices: "dev", "prod"]
  --port, -p  port                                        [number] [default: 80]

Argument check failed: data => {
    return !isNaN(data.port);
}

Approach 2 prints out only what I coded

...
.check(data => {
  if (isNaN(data.port)) {
    throw new Error('port is not a number');
  } 
  else {
    return data.port;
  }
})

ts-node src/index.ts -e dev -p abc
Options:
  --help      Show help                                                [boolean]
  --version   Show version number                                      [boolean]
  --env, -e   app environment                [required] [choices: "dev", "prod"]
  --port, -p  port                                        [number] [default: 80]

port is not a number

Yargs API says If fn throws or returns a non-truthy value, show the thrown error, usage information, and exit., so I modified check() so that it threw an error if data.port is NaN and worked like above.

code of conduct - report abuse