~ 4 min read
Getting Started with CLI Arguments in Node.js
Command-line interfaces (CLIs) are a powerful way to interact with software, especially for developers who prefer automation and scripting. In this guide, you’ll learn how to enhance your Node.js CLI applications using the built-in util.parseArgs
API. By exploring the agent-rules
project, you’ll gain insights into implementing dual-mode operations, validating inputs, and testing your CLI tools effectively. This tutorial is designed for intermediate Node.js developers familiar with CLI tools and basic scripting.
Prerequisites
Before diving into the tutorial, ensure you have the following:
- Node.js: Current LTS version
- Basic knowledge: Familiarity with CLI tools and Node.js scripting
- Git: For cloning repositories
Setting Up the Environment
To get started, you’ll need to set up your development environment. Follow these steps to clone the agent-rules
repository and install the necessary dependencies.
1. Clone the Repository
The agent-rules
project is a CLI tool designed to generate security-focused instructions for AI coding assistants. Start by cloning the repository:
git clone https://github.com/lirantal/agent-rules.git
cd agent-rules
2. Install Dependencies
Next, install the required Node.js packages using npm:
npm install
This step ensures that all necessary packages are available for the project to run smoothly.
Understanding CLI Argument Parsing
Node.js provides a built-in API for parsing command-line arguments, which simplifies the process of handling user inputs. The util.parseArgs
API is a powerful tool for this purpose.
Why Use util.parseArgs
?
Using built-in Node.js modules for CLI development offers several benefits:
- Simplicity: Reduces the need for external dependencies.
- Performance: Optimized for Node.js runtime.
- Security: Minimizes the risk of injection attacks by validating inputs.
Example: Parsing Command-Line Arguments
Here’s a basic example of how to parse command-line arguments using util.parseArgs
:
import { parseArgs } from 'node:util';
function parseCommandLineArgs(): CliArgs {
const { values } = parseArgs({
args: process.argv.slice(2),
options: {
app: { type: 'string', short: 'a' },
topics: { type: 'string', multiple: true, short: 't' },
help: { type: 'boolean', short: 'h' },
version: { type: 'boolean', short: 'v' }
}
});
return values;
}
Why this matters: This function demonstrates how to set up argument parsing using Node.js built-in utilities.
Verify: Run the CLI with various flags to see parsed output.
Implementing Dual-Mode CLI
The agent-rules
project supports both interactive and automated workflows. This dual-mode operation is crucial for flexibility in different environments.
Step-by-Step Guide
-
Add Command-Line Argument Support
Modify your CLI application to accept command-line arguments. This involves defining the expected options and their types.
const args = parseCommandLineArgs();
-
Implement Interactive Mode
Use the
@clack/prompts
library to create an interactive session when no arguments are provided.import { prompt } from '@clack/prompts'; async function interactiveMode() { const app = await prompt('Enter the app name:'); const topics = await prompt('Enter topics (comma-separated):'); // Process inputs }
-
Switch Between Modes
Determine the mode based on the presence of command-line arguments.
if (Object.keys(args).length === 0) { interactiveMode(); } else { // Process command-line arguments }
Why this matters: Dual-mode operation allows users to choose between automation and manual interaction, enhancing usability.
Validating and Handling Arguments
Proper validation and error handling are essential for robust CLI applications. This ensures that users receive clear feedback when they provide invalid inputs.
Techniques for Validation
-
Validate CLI Inputs
Ensure that the provided arguments meet the expected criteria.
function validateCliArgs(args: CliArgs): void { if (args.app && !AVAILABLE_APPS.includes(args.app)) { console.error(`Error: Invalid app "${args.app}". Available apps: ${AVAILABLE_APPS.join(', ')}`); process.exit(1); } }
Why this matters: Validating inputs prevents errors and provides helpful feedback to users.
Verify: Test with invalid app names to trigger validation errors.
-
Handle Errors Gracefully
Use try-catch blocks to manage unexpected errors and provide meaningful messages.
try { validateCliArgs(args); } catch (error) { console.error('An error occurred:', error.message); process.exit(1); }
Why this matters: Effective error handling improves the user experience by preventing crashes and guiding users to correct their inputs.
Testing CLI Applications
Testing is a critical part of developing reliable CLI tools. It ensures that your application behaves as expected under various scenarios.
Writing Unit Tests
-
Test Argument Parsing
Use the Node.js
assert
module to write unit tests for your argument parsing logic.import assert from 'node:assert'; assert.deepStrictEqual(parseCommandLineArgs(['--app', 'myApp']), { app: 'myApp' });
-
Simulate CLI Interactions
Use
spawnSync
to simulate command-line interactions in your tests.import { spawnSync } from 'node:child_process'; const result = spawnSync('node', ['cli.js', '--app', 'myApp']); assert.strictEqual(result.status, 0);
Why this matters: Testing ensures that your CLI application handles different input scenarios correctly and reliably.
Conclusion
By mastering CLI argument parsing in Node.js, you can build powerful and flexible command-line tools. This guide covered the essentials of using the util.parseArgs
API, implementing dual-mode operations, validating inputs, and testing your applications. With these skills, you’re well-equipped to enhance your Node.js CLI projects.
- Try the updated
agent-rules
CLI with your own AI app configurations. - Follow on X/Twitter for new guides and security research.
- Explore more code examples and related work on GitHub.
For further reading, check out the Node.js util
module documentation and the Agent Rules GitHub Repository.