I want to write a little CLI tool using yargs and typescript.
The first goal is to run the program(I will call it something in this question) when the empty command and --input is given.(e.g. something --input="../hello.there"). I used the default route to handle this.
The second is to ignore or show help on every command except help. However, I used default router '*' so it capture every command that is not defined. Is there any good way to compare undefined routes and ''?
This is the code of my program.
import yargs from 'yargs/yargs';
import { hideBin } from 'yargs/helpers';
import { getPath } from './parser';
import { ArgumentsCamelCase } from 'yargs';
yargs(process.argv)
.command({
command: '*',
describe: "Parse a file's contents",
builder: function (yargs) {
return yargs.option('i', {
alias: 'input',
describe: 'the URL to make an HTTP request to',
type: 'string',
});
},
handler() {
console.log('hi');
},
})
.help()
.parse();
I found the method. The basic idea is if there is a command, then
process.argv[2]does not start with--. By checking this condition in the handler function, we can know that this is a valid empty command or an invalid command.