Last active
January 27, 2021 07:42
-
-
Save wsams/2d3ee1ab4ed688aa8d82edd8c2cca5d8 to your computer and use it in GitHub Desktop.
A tiny CLI framework for writing Node JS command line tools or scripts. It provides a simple way to handle non-positional arguments using a flag based system.
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 { execSync } = require('child_process'); | |
const args = {}; | |
const argv = process.argv.slice(2); | |
if (argv.length === 0) usage(); | |
argv.forEach((arg, i) => args[arg] = argv[i + 1]); | |
// Every flag must have a value even if it's not being used | |
// Instead of a boolean --version you might use `-v true` | |
const inputFileName = args['-i']; | |
const outputFileName = args['-o']; | |
function usage() { | |
console.log('Usage: node tiny-cli.js -i <input filename> -o <output filename>'); | |
console.log('Example: node tiny-cli.js -i in.md -o out.pdf'); | |
process.exit(0); | |
} | |
function verifyArg(arg) { | |
// override this function with your own validation | |
return true; | |
} | |
if (!verifyArg(inputFilename)) { | |
console.error('Please verify your input filename'); | |
process.exit(1); | |
} | |
if (!verifyArg(outputFilename)) { | |
console.error('Please verify your output filename'); | |
process.exit(1); | |
} | |
console.log('Do some work'); | |
const directoryListing = execSync('ls /home/foobar'); | |
console.log(directoryListing); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment