nodal-cli
v1.2.0
Published
A simple yet robust command-line interface (CLI) builder for Node.js applications.
Maintainers
Readme
nodal-cli
A simple but powerful event-driven CLI framework for Node.js.
Designed to help you build interactive command-line applications with support for commands, arguments, options (flags), validation, and built-in help and exit functionality.
Features
- 📦 Command registration with descriptions, arguments, and options
- ✅ Argument validation and optional arguments
- 🏷️ Flag parsing with support for multiple hyphens (e.g.,
--flag--nested) - 📚 Built-in
helpandexitcommands - 🔁 Interactive input loop using
readline - 🎯 Event-driven command handling via
EventEmitter - 🧪
run()method to simulate command input (great for testing)
Installation
npm install nodal-cliUsage
const CommandLine = require('nodal-cli');
const cli = new CommandLine();
// Register commands with their arguments, options, and optional validation rules
CommandLine.registerCommand('hello', [], [], {});
CommandLine.registerCommand('greet', 'Greets a user.', ['message'], ['loud'], {});
CommandLine.registerCommand('calculate', 'Adds two numbers.', ['num1', 'num2'], [], {
num1: (value) => /^\d+$/.test(value), // Example: Validate if num1 is a number
num2: (value) => /^\d+$/.test(value), // Example: Validate if num2 is a number
});
CommandLine.registerCommand('exit', 'Exits the CLI.');
// Listen for command events
cli.on('hello', (args) => {
console.log('Hello!');
});
cli.on('greet', (args, options) => {
let message = `Greeting: ${args.message || 'What would you like to say?'}`;
if (options.includes('loud')) {
message = message.toUpperCase() + '!!!';
}
console.log(message);
if (!args.message) {
cli.run('help greet');
}
});
cli.on('calculate', (args) => {
if (args.num1 && args.num2) {
const sum = parseInt(args.num1) + parseInt(args.num2);
console.log(`The sum is: ${sum}`);
} else {
console.log('Please provide two numbers to calculate.');
cli.run('help calculate');
}
});
cli.on('exit', () => {
console.log('Exiting CLI interface...');
cli.stop();
process.exit(0);
});
// Start the CLI prompt
cli.listen();
// You can also programmatically run commands:
// setTimeout(() => {
// cli.run('hello --exciting');
// }, 2000);Important Notes
Required arguments must have associated validation rules. For example:
const CommandLine = require("nodal-cli") const cli = new CommandLine() CommandLine.registerCommand("echo","Echos the provided message.",["message"], [], { message: (value) => true }) cli.on("echo",(args) => { console.log(args.message) })> echo hello hello > echo Invalid Arguement list Usage: echo <message>
API Reference
CommandLine.registerCommand(command: string, description: string, args?: string[], options?:string[], validationRules?: Record<string, (value:string) => boolean>): [boolean,string]
Registers a new CLI command.
command: Name of the command (case-insensitive)description: Description shown in helpargs: Array of argument namesoptions: Array of option names (flags) without--validationRules: Object mapping argument names to validation functions- Returns: An array containing a boolean (
truefor success,falsefor failure) and a message string.
cli.on(commandName:string, callback:(args:Record<string, string>, options:string[])): void
Listen for a registered commandName and receive:
args: Object with argument names (as registered) and their corresponding valuesoptions: Array of enabled option flags (lowercase, without--)
cli.listen(): Promise<void>
Starts the prompt loop and asynchronously awaits user input.
cli.pause(): void
Pauses the CLI, stopping it from listening for new input. The prompt is hidden. Useful when performing long tasks
cli.resume(): Promise<void>
Resumes the CLI, redisplaying the prompt (> ) and allowing it to listen for new input again asynchronously. Useful when after performing long tasks
cli.stop(): void
Closes the readline interface, effectively stopping the CLI.
cli.run(commandString:string): Promise<void>
Asynchronously simulates typing a command—useful for scripting or testing.
Built-in Commands
help [command]:- Without an argument, lists all available commands and their argument syntax (e.g.,
<argument>) and options (e.g.,--option). - With a
commandargument, shows the specific usage for that command, including its arguments (with?indicating potentially optional arguments based on the absence of validation rules) and available options.
- Without an argument, lists all available commands and their argument syntax (e.g.,
exit:- Closes the CLI interface and emits an
exitevent.
- Closes the CLI interface and emits an
Example
> greet Alice --shout
HELLO, ALICE!License
MIT
Copyright © 2025 MeroSsSany
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.#� �n�o�d�a�l�-�c�l�i� � �
