Working with Command-Line Arguments
1. Accessing process.argv Array
| Snippet | Result |
|---|---|
process.argv.slice(2) | Just user args |
process.execArgv | Args to node itself (e.g. --inspect) |
2. Parsing Arguments Manually
Example: Tiny parser
const args = process.argv.slice(2);
const opts = {};
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith("--")) opts[args[i].slice(2)] = args[i+1];
}
3. Using util.parseArgs for CLI
Example: util.parseArgs v18.3+
import { parseArgs } from "node:util";
const { values, positionals } = parseArgs({
options: {
port: { type: "string", short: "p", default: "3000" },
verbose: { type: "boolean", short: "v" }
},
allowPositionals: true
});
| Option Type | Notes |
|---|---|
string | Captures next token |
boolean | Flag presence |
multiple: true | Collect array |
4. Using commander for CLI
Example
import { Command } from "commander";
const program = new Command();
program
.name("mycli")
.option("-p, --port <number>", "port", "3000")
.command("serve").action(() => startServer())
.parse();
5. Using yargs for Argument Parsing
| Feature | Notes |
|---|---|
| Subcommands | .command("build", ...) |
| Auto help/version | .help().version() |
| Type coercion | .number("port") |
| Validation | .demandOption(["file"]) |
6. Handling Flags and Options (--flag, -f)
| Form | Convention |
|---|---|
--name value | Long option |
--name=value | Long with equals |
-n value / -nv | Short / combined |
--no-color | Negated boolean |
7. Using Positional Arguments
| Tool | Access |
|---|---|
| util.parseArgs | positionals |
| commander | .argument("<file>") |
| yargs | argv._ |
8. Implementing Subcommands
Example: commander subcommands
program
.command("user <action>")
.description("manage users")
.action((action) => { /* ... */ });
9. Adding Help and Usage Info
| Library | Auto Help Flag |
|---|---|
| commander | -h, --help |
| yargs | --help |
| util.parseArgs | Build manually |
10. Validating User Input
| Strategy | Example |
|---|---|
| Schema validation | Zod / Joi |
| Library hooks | commander .choices([...]) |
| Custom predicates | Throw with friendly message |
11. Creating Interactive CLIs
| Library | Use |
|---|---|
| Inquirer / Prompts | Interactive prompts |
| Enquirer | Lightweight prompts |
| Chalk / Picocolors | Colorized output |
| Ora | Spinners |
| Ink | React-like CLI rendering |