Skip to content

Instantly share code, notes, and snippets.

@felippe-regazio
Created May 25, 2023 00:55
Show Gist options
  • Save felippe-regazio/e00b00509553141d4cfb9877679c7ab5 to your computer and use it in GitHub Desktop.
Save felippe-regazio/e00b00509553141d4cfb9877679c7ab5 to your computer and use it in GitHub Desktop.
Just a dummy node CLI
/*
Simple and dummy CLI in node. Usage
node cli.js <command> <-flags> <--options[=value]> <arguments>
Example:
node cli.js
node cli.js help
node cli.js hello
node cli.js hello -a
node cli.js hello --to=Someone
node cli.js hello -a --to=Someone
*/
const argv = process.argv.slice(2);
const AVAILABLE_COMMANDS = [ 'help', 'hello' ];
const INSTRUCTION = {
command: argv[0],
arguments: argv.slice(1).filter(item => !item.startsWith('-')),
flags: argv.filter(item => item.startsWith('-') && !item.startsWith('--')),
options: argv.filter(item => item.startsWith('--')).map(item => item.split('='))
.reduce((acc, item) => ({ ...acc, ...{[item[0]]: item[1] }}), {})
}
// ------------------------------------------------
function help() {
console.log(`Simple Node CLI Example. Commands available
help prints help
hello prints hello
-a prints hello to all
--to=<person> prints hello to a given name`);
}
function hello(toAll, toPerson) {
const and = toAll && toPerson && 'and';
console.log(`hello ${toAll} ${and} ${toPerson}`)
}
// ------------------------------------------------
if (INSTRUCTION.command === 'help' || !AVAILABLE_COMMANDS.includes(INSTRUCTION.command)) {
help();
}
if (INSTRUCTION.command === 'hello') {
const toAll = INSTRUCTION.flags.includes('-a') ? 'everybody' : '';
const toPerson = INSTRUCTION.options['--to'] || '';
hello(toAll, toPerson);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment