🖥️ wrapCLI
A lightweight wrapper for creating CLI (Command-Line Interface) commands in Node.js, with automatic argument parsing, type conversion, help support, and async handling.
Overview
wrapCLI allows you to wrap a regular JavaScript function and run it as a CLI command. It:
- Parses command-line arguments (
process.argv). - Supports positional and named arguments.
- Automatically converts argument strings to boolean, number, or string.
- Provides built-in help functionality with aliases.
- Handles async functions and errors gracefully.
Functions
1. tryParseValue(value)
Converts string values to their appropriate types.
1tryParseValue("true"); // → true2tryParseValue("false"); // → false3tryParseValue("123.5"); // → 123.54tryParseValue("hello"); // → "hello"
- Booleans (
true/false) - Numbers (
parseFloat) if numeric - Strings otherwise
2. parseArgs(argv)
Parses an array of CLI arguments into positional and named arguments.
Example:
1node cli.js foo bar --count 3 --verbose true
Output:
1{2 positional: ["foo", "bar"],3 named: { count: 3, verbose: true }4}
Behavior:
--key valuebecomesnamed[key] = value.- Multiple values after a flag become an array.
- Flag with no value →
true. - Single-value arrays are simplified to a single value.
3. showHelp(meta)
Displays a help message using a metadata object.
1const meta = {2 description: "Example CLI tool",3 args: [{ name: "input", type: "string", required: true }],4 named: [{ name: "verbose", type: "boolean" }]5};7showHelp(meta);
Output:
📘 Example CLI tool
Positional arguments:
input (required) <string> —
Named options:
--verbose <boolean> —
Use "--help" to show this message.
4. wrapCLI(fn, meta, aliases)
Wraps a JavaScript function fn as a CLI command.
1import { wrapCLI } from 'hbh-nodes';3function greet(name, options) {4 const prefix = options?.loud ? "HELLO" : "Hello";5 return `${prefix} ${name}!`;6}8const cli = wrapCLI(greet, {9 description: "Greet someone",10 args: [{ name: "name", type: "string", required: true }],11 named: [{ name: "loud", type: "boolean" }]12});14cli(); // Run from Node.js
Features:
- Checks for help flags (
--helpor-h) viaaliases. - Spreads positional arguments to the function.
- Optionally passes named arguments as the last object.
- Handles async functions automatically.
- Catches exceptions and logs errors.
Example Usage
1# Positional argument2node cli.js Alice4# Named argument5node cli.js Alice --loud true7# Help8node cli.js --help9node cli.js -h
Notes
- Named arguments repeated are collected as arrays.
tryParseValueautomatically converts numeric and boolean strings.- Help output is fully customizable via the
metaobject.
This wrapper is perfect for lightweight CLI tools without installing external dependencies like yargs or commander.
It keeps argument parsing simple, type-safe, and easy to extend with aliases or async handlers.