Created
June 27, 2021 03:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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