{"id":12966,"library":"cli-args-parser","title":"CLI Arguments Parser with Schema Validation","description":"cli-args-parser is an expressive and modern TypeScript library for parsing command-line arguments in Node.js environments (requiring Node.js >=18.0.0). Its core differentiator is the integration of Zod for robust, declarative schema validation, ensuring that CLI inputs conform to predefined types and structures. This prevents common errors by providing immediate feedback on invalid arguments or missing required options. Currently stable at version 1.0.6, the library focuses on a straightforward API for defining expected arguments, options, and flags, making it suitable for building well-structured and user-friendly CLI tools. Unlike more opinionated or heavier alternatives, it provides schema-driven validation out-of-the-box, simplifying argument processing and error handling. Release cadence appears stable with incremental 1.x updates.","status":"active","version":"1.0.6","language":"javascript","source_language":"en","source_url":"https://github.com/forattini-dev/cli-args-parser","tags":["javascript","cli","parser","args","arguments","terminal","command-line","options","flags","typescript"],"install":[{"cmd":"npm install cli-args-parser","lang":"bash","label":"npm"},{"cmd":"yarn add cli-args-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add cli-args-parser","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used for defining and validating argument schemas. This is a core feature of cli-args-parser.","package":"zod","optional":false}],"imports":[{"note":"The library primarily uses ES Modules. Direct CommonJS require() may lead to issues or require specific configuration for interoperability in older Node.js versions.","wrong":"const Parser = require('cli-args-parser').Parser;","symbol":"Parser","correct":"import { Parser } from 'cli-args-parser';"},{"note":"Zod is a peer dependency used for schema definition. It's typically imported as a named export `z` for convenience.","wrong":"import * as z from 'zod';","symbol":"z","correct":"import { z } from 'zod';"}],"quickstart":{"code":"import { Parser } from 'cli-args-parser';\nimport { z } from 'zod';\n\n// 1. Define your CLI argument schema using Zod\nconst argsSchema = z.object({\n  name: z.string().min(1).describe('The name to greet.'),\n  age: z.number().int().positive().optional().describe('The user\\'s age.'),\n  verbose: z.boolean().default(false).describe('Enable verbose output.'),\n  output: z.enum(['json', 'text']).default('text').describe('Output format.'),\n}).strict(); // Use .strict() to disallow unknown arguments\n\n// 2. Initialize the parser with your schema and optional metadata\nconst parser = new Parser({\n  schema: argsSchema,\n  usage: 'Usage: my-cli --name <name> [--age <age>] [--verbose] [--output <format>]',\n  description: 'A simple greeting CLI application with schema validation.',\n  version: '1.0.6', // Make sure to match your package's actual version\n  examples: [\n    'my-cli --name Alice --age 30 --verbose',\n    'my-cli --name Bob --output json'\n  ]\n});\n\n// 3. Parse command-line arguments (excluding 'node' and script path)\ntry {\n  const parsedArgs = parser.parse(process.argv.slice(2));\n\n  if (parsedArgs.output === 'json') {\n    console.log(JSON.stringify(parsedArgs, null, 2));\n  } else {\n    let greeting = `Hello, ${parsedArgs.name}!`;\n    if (parsedArgs.age) {\n      greeting += ` You are ${parsedArgs.age} years old.`;\n    }\n    if (parsedArgs.verbose) {\n      greeting += ` (Verbose mode active.)`;\n    }\n    console.log(greeting);\n  }\n} catch (error) {\n  if (error instanceof Error) {\n    console.error(`CLI Error: ${error.message}`);\n  } else {\n    console.error('An unknown error occurred during CLI parsing.');\n  }\n  process.exit(1); // Exit with a non-zero code on error\n}","lang":"typescript","description":"This quickstart demonstrates how to define a CLI argument schema using Zod, parse arguments with `cli-args-parser`, and handle validation errors, showcasing basic typed input and flag usage."},"warnings":[{"fix":"Upgrade your Node.js environment to version 18.0.0 or newer. Ensure your project's `package.json` `type` field is set to `module` or use `.mjs` file extensions for ESM files.","message":"This library requires Node.js version 18.0.0 or higher. Running in older Node.js environments will result in errors, particularly with ES Module syntax.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Add `zod` to your project's dependencies. Consult Zod's documentation for advanced schema definition and validation patterns.","message":"The library relies on 'zod' for schema definition and validation. You must install 'zod' as a direct dependency in your project: `npm install zod` or `yarn add zod`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"When defining your `z.object` schema, chain `.strict()` at the end, e.g., `z.object({...}).strict()`.","message":"By default, Zod schemas are not 'strict' and will allow unknown properties. To ensure your CLI parser rejects arguments not defined in your schema, always apply `.strict()` to your Zod object schema.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Manually construct detailed help messages or integrate with a separate library for advanced help generation if required for complex CLIs. The `usage`, `description`, `version`, and `examples` fields in the `Parser` constructor are intended for basic display.","message":"Unlike some other CLI parsers (e.g., Commander, Yargs), `cli-args-parser` does not provide extensive built-in functionality for generating complex help text or subcommands automatically beyond what's defined in the `usage` and `description` options. You are responsible for structuring your help output using the provided metadata.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Convert your project or the offending file to an ES Module by setting `\"type\": \"module\"` in your `package.json` and using `import` statements, or by renaming your file to `.mjs`.","cause":"Attempting to import `cli-args-parser` using CommonJS `require()` syntax in a CommonJS module, while the library is ESM-only.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module ...cli-args-parser/dist/index.js from ... not supported."},{"fix":"Check the arguments passed to your CLI against the defined Zod schema. Ensure types match (e.g., number for `z.number()`), all required arguments are present, and no extraneous arguments are provided if the schema is strict. The error message usually provides details on which specific validation failed.","cause":"The command-line arguments provided do not match the schema defined using Zod. This could be due to incorrect types, missing required arguments, or unrecognized arguments (if `.strict()` is used).","error":"CLI Error: Validation Error: Invalid input"},{"fix":"Ensure that argument values match their expected Zod types. For numbers, provide numeric values. For booleans, ensure flags are handled correctly (e.g., presence implies `true`, absence `false` for `z.boolean().default(false)`).","cause":"An argument expected to be a number (e.g., `--age 30`) was provided as a non-numeric string, and Zod's validation failed to coerce or validate the type.","error":"ZodError: [ { \"code\": \"invalid_type\", \"expected\": \"number\", \"received\": \"string\", \"path\": [ \"age\" ], \"message\": \"Expected number, received string\" } ]"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}