Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Created June 27, 2021 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isurfer21/e7c9d38333f2798ba2493a80d461845e to your computer and use it in GitHub Desktop.
Save isurfer21/e7c9d38333f2798ba2493a80d461845e to your computer and use it in GitHub Desktop.
Simplest CLI based node.js app with in-built argument parser without any dependencies
const flags = { _: [] };
process.argv.forEach((s, e) => {
if (e >= 2)
if (/^[\-\-]{1,2}.+[\=\:].*$/.test(s)) {
let e = s.split(/[\=\:]/),
l = e[0].lastIndexOf("-");
l < 2 && (flags[e[0].substring(l + 1)] = e[1]);
} else if (/^[\-\-]{1,2}.+$/.test(s)) {
let e = s.lastIndexOf("-");
e < 2 && (flags[s.substring(e + 1)] = !0);
} else flags._.push(s);
});
if (flags.h || flags.help) {
console.log(`
Options:
-h --help display help menu
-v --version show app version
-n --name=NAME provide your name
Usages:
$ node index.js (-h|--help)
$ node index.js (-v|--version)
$ node index.js (-n=AK|--name="Abhishek Kumar")
Examples:
$ node index.js --help
$ node index.js --name="Abhishek Kumar"
`);
} else if (flags.v || flags.version) {
console.log(`App CLI version 1.0.0`);
} else {
// Your application logic
console.log(`Hello, ${flags.n || flags.name}!`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment