Construct Node.js CLI's with ease, inspired by Regular Expression Syntax.
- Create
cli.js
and define a basic command:
#!/usr/bin/env node
const cmdx = require("cmdx");
const args = cmdx
.usage("<Number:a> <op> <Number:b> [--floor, --round]?")
.arg("op", {values: ["+", "-", "/", "*"]})
.parse(process.argv);
if (!args) return console.log("Unrecognized Command");
let value, a = args.a, b = args.b;
switch (args.op) {
case "+": value = a + b; break;
case "-": value = a - b; break;
case "*": value = a * b; break;
case "/": value = a / b; break;
default: value = 0;
}
if (args["--floor"]) value = Math.floor(value);
if (args["--round"]) value = Math.round(value);
console.log(`${a} ${op} ${b} = ${value}`);
- Create
package.json
{
"bin": {
"math": "./cli.js"
}
}
- Install globally for use in your terminal
npm install -g
- Run the math command
> math 1 + notanumber
Unrecognized Command
> math 1.2 + 2.3
3.5
> math 1.2 * 2.3 --floor
2