{"id":13723,"library":"opts","title":"opts Command-Line Argument Parser","description":"`opts` is a lightweight command-line argument parser for Node.js, currently at version 2.0.2. It provides functionalities for parsing short (`-s`) and long (`--long`) options, as well as positional arguments, and automatically generates help text. A key differentiator is its minimal footprint and zero external dependencies, designed to work as a standalone JavaScript file without requiring NPM or other package managers. This makes it suitable for projects prioritizing simplicity and a small bundle size. While primarily a plain JavaScript library, it ships with TypeScript definitions for enhanced development experience. `opts` processes arguments through callbacks associated with each option, rather than returning a structured object of parsed values. Its stable nature suggests a focus on maintenance, offering a robust solution for basic to moderate CLI parsing needs.","status":"active","version":"2.0.2","language":"javascript","source_language":"en","source_url":"https://github.com/khtdr/opts","tags":["javascript","command line parser","opts","args","help text","typescript"],"install":[{"cmd":"npm install opts","lang":"bash","label":"npm"},{"cmd":"yarn add opts","lang":"bash","label":"yarn"},{"cmd":"pnpm add opts","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Use named import for the main `parse` function in ESM/TypeScript environments. For CommonJS, access as `require('opts').parse`.","wrong":"import opts from 'opts'; // 'opts.parse is not a function'","symbol":"parse","correct":"import { parse } from 'opts';"},{"note":"Import the `Option` interface for type-checking when defining command-line options in TypeScript.","wrong":"import { IOption } from 'opts';","symbol":"Option","correct":"import { Option } from 'opts';"},{"note":"Imports all named exports into a single `opts` namespace object. Useful for accessing all library features like `opts.parse` and `opts.Option`.","wrong":"const opts = require('opts'); // If expecting ESM-style module resolution in TS/ESM code.","symbol":"* as opts (namespace import)","correct":"import * as opts from 'opts';"}],"quickstart":{"code":"import { parse, Option } from 'opts';\n\nconst options: Option[] = [\n  {\n    short: 'h',\n    long: 'help',\n    description: 'Display this help message.',\n    callback: function () {\n      console.log('Usage: my-cli-tool [options] <command>');\n      process.exit(0);\n    },\n  },\n  {\n    short: 'v',\n    long: 'version',\n    description: 'Show version and exit.',\n    callback: () => {\n      console.log('my-cli-tool v1.0.0');\n      process.exit(0);\n    },\n  },\n  {\n    short: 'p',\n    long: 'port',\n    description: 'Specify the port number for the server.',\n    value: true, // Indicates that this option expects a value\n    required: false,\n    callback: (value) => {\n      if (value && typeof value === 'string') {\n        process.env.APP_PORT = value; // Store value globally or in a local state\n        console.log(`Port set to: ${value}`);\n      }\n    }\n  }\n];\n\n// Positional arguments can be defined in a second array, e.g., [{ name: 'command', required: true }]\n// For this example, we're not formally defining positional arguments but will process them heuristically.\n\nparse(options, [], true); // Parse options, no defined arguments array, enable automatic help text\n\n// Access parsed values from process.env if set by callbacks, or default\nconst serverPort = process.env.APP_PORT ?? '3000';\n\n// Simulate execution based on arguments. If --help or --version caused an exit, we wouldn't reach here.\nconst rawArgs = process.argv.slice(2);\nconst command = rawArgs.find(arg => !arg.startsWith('-') && !arg.includes('=')); // Simple heuristic for a command\n\nif (command === 'start') {\n  console.log(`Starting application server on port ${serverPort}...`);\n  // Add actual server start logic here\n} else if (command === 'stop') {\n  console.log('Stopping application...');\n} else if (command) {\n  console.error(`Error: Unknown command '${command}'`);\n  process.exit(1);\n} else {\n    console.log(`No specific command provided. Application running on default port ${serverPort}.`);\n    // Default application behavior\n}\n","lang":"typescript","description":"This example demonstrates how to define command-line options with short and long forms, descriptions, and callbacks using TypeScript, enabling automatic help generation and basic argument parsing for a CLI tool. It also shows how to handle option values and simple positional commands."},"warnings":[{"fix":"Ensure your `tsconfig.json` `moduleResolution` is set appropriately (e.g., `Node16` or `Bundler`) and consistently use explicit named or namespace imports in ESM contexts.","message":"When migrating from CommonJS `require('opts')` to ESM `import`, use `import { parse, Option } from 'opts';` for named imports or `import * as opts from 'opts';` for namespace imports. Directly using `import opts from 'opts';` might lead to undefined `parse` errors depending on your TypeScript configuration or bundler due to how `opts` exposes its API.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Design your option callbacks to directly invoke application logic or to store parsed values in a shared data structure (e.g., a mutable configuration object passed by reference) that can be accessed after `opts.parse` completes.","message":"`opts` processes arguments primarily through callbacks associated with each option and does not return a single object containing all parsed options and arguments. This design requires developers to implement custom logic within callbacks to handle side effects or to store parsed values in a mutable object or global state (e.g., `process.env`) if they need to aggregate results for later use.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For standalone usage, manually download `opts.d.ts` from the GitHub repository and ensure it's included in your TypeScript project's `files` or `include` array within `tsconfig.json` to enable full type checking and IDE support.","message":"If `opts` is downloaded and included as a standalone JavaScript file without `npm install`, TypeScript type definitions (`opts.d.ts`) will not be automatically discovered. This will result in a lack of type safety and editor autocomplete unless the `.d.ts` file is manually downloaded and configured in your `tsconfig.json`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Evaluate your CLI's complexity before choosing `opts`. For applications requiring advanced features such as subcommands, extensive validation, or custom help formatting, consider more comprehensive libraries like `commander.js` or `yargs`.","message":"`opts` is designed as a minimalist parser and does not include advanced features like complex schema validation, nested commands, or sophisticated environment variable integration that are common in more feature-rich CLI libraries. Its focus is on straightforward option and argument parsing with callbacks.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"search_vec":"'2.0.2':21 'arg':139 'argument':5,14,37,99 'associ':102 'automat':39 'basic':128 'bundl':80 'callback':101 'cli':131 'command':3,12,135 'command-lin':2,11 'current':18 'definit':92 'depend':53 'design':54 'develop':95 'differenti':45 'enhanc':94 'experi':96 'extern':52 'file':61 'focus':120 'footprint':49 'function':24 'generat':40 'help':41,140 'javascript':60,86,134 'key':44 'librari':87 'lightweight':10 'line':4,13,136 'long':30,31 'mainten':122 'make':70 'manag':68 'minim':48 'moder':130 'natur':117 'need':133 'node.js':17 'npm':64 'object':111 'offer':123 'opt':1,7,97,138 'option':32,105 'packag':67 'pars':26,113,132 'parser':6,15,137 'plain':85 'posit':36 'primarili':83 'priorit':75 'process':98 'project':74 'provid':23 'rather':106 'requir':63 'return':108 'robust':125 'ship':89 'short':27 'simplic':76 'size':81 'small':79 'solut':126 'stabl':116 'standalon':59 'structur':110 'suggest':118 'suitabl':72 'text':42,141 'typescript':91,142 'valu':114 'version':20 'well':34 'without':62 'work':56 'zero':51","created_at":"2026-04-20T01:55:58.218891+00:00","updated_at":"2026-04-20T01:55:58.218891+00:00","problems":[{"fix":"For ESM/TypeScript, use `import { parse } from 'opts';` or `import * as opts from 'opts';`. For CommonJS, ensure `var opts = require('opts');` then call `opts.parse(...)`.","cause":"The `opts` module was imported incorrectly in an ESM/TypeScript context (e.g., `import opts from 'opts';`) or `require()` was used in an environment where named exports are expected differently.","error":"TypeError: opts.parse is not a function"},{"fix":"Run `npm install opts` or `yarn add opts`. If using the standalone version, ensure `opts.js` is in your project and referenced correctly, e.g., `require('./opts.js')` or `import { parse } from './opts.js';` depending on your module system.","cause":"The `opts` package is not installed via npm, or if using the standalone version, the `opts.js` file is not correctly referenced by the module resolver.","error":"Cannot find module 'opts'"},{"fix":"Set `value: true` in your `Option` definition if the option expects a value to follow it. For boolean flags that do not take a value (e.g., `--verbose`), `value` should be `false` or omitted. The actual parsed value is then passed to the option's `callback` function.","cause":"This TypeScript error occurs when providing an incorrect type to the `value` property of an `Option` object. For options that expect a runtime value (e.g., `--port 8080`), `value` should be set to `true` (a boolean indicating a value is expected), not a literal string or number.","error":"Argument of type 'string' is not assignable to parameter of type 'boolean | string | number | string[] | undefined'."}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.1.1","cli_name":"","cli_version":null,"type":"library","homepage":"http://khtdr.com/opts","github":"https://github.com/khtdr/opts","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/opts","openapi_spec":null,"status_page":null,"smithery":null,"categories":[],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}