Registry / opts
library0.1.1jsnpmunverified

`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.

npm install opts
INSTALL
IMPORT
SIG · OPTS
O
opts
javascriptv0.1.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

parse
import { parse } from 'opts';
import opts from 'opts'; // 'opts.parse is not a function'
Use named import for the main `parse` function in ESM/TypeScript environments. For CommonJS, access as `require('opts').parse`.
Option
import { Option } from 'opts';
import { IOption } from 'opts';
Import the `Option` interface for type-checking when defining command-line options in TypeScript.
* as opts (namespace import)
import * as opts from 'opts';
const opts = require('opts'); // If expecting ESM-style module resolution in TS/ESM code.
Imports all named exports into a single `opts` namespace object. Useful for accessing all library features like `opts.parse` and `opts.Option`.

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.

import { parse, Option } from 'opts'; const options: Option[] = [ { short: 'h', long: 'help', description: 'Display this help message.', callback: function () { console.log('Usage: my-cli-tool [options] <command>'); process.exit(0); }, }, { short: 'v', long: 'version', description: 'Show version and exit.', callback: () => { console.log('my-cli-tool v1.0.0'); process.exit(0); }, }, { short: 'p', long: 'port', description: 'Specify the port number for the server.', value: true, // Indicates that this option expects a value required: false, callback: (value) => { if (value && typeof value === 'string') { process.env.APP_PORT = value; // Store value globally or in a local state console.log(`Port set to: ${value}`); } } } ]; // Positional arguments can be defined in a second array, e.g., [{ name: 'command', required: true }] // For this example, we're not formally defining positional arguments but will process them heuristically. parse(options, [], true); // Parse options, no defined arguments array, enable automatic help text // Access parsed values from process.env if set by callbacks, or default const serverPort = process.env.APP_PORT ?? '3000'; // Simulate execution based on arguments. If --help or --version caused an exit, we wouldn't reach here. const rawArgs = process.argv.slice(2); const command = rawArgs.find(arg => !arg.startsWith('-') && !arg.includes('=')); // Simple heuristic for a command if (command === 'start') { console.log(`Starting application server on port ${serverPort}...`); // Add actual server start logic here } else if (command === 'stop') { console.log('Stopping application...'); } else if (command) { console.error(`Error: Unknown command '${command}'`); process.exit(1); } else { console.log(`No specific command provided. Application running on default port ${serverPort}.`); // Default application behavior }
Debug
Known issues
gotchaWhen 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.
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.
affects: >=2.0.0
gotcha`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.
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.
affects: >=1.0.0
gotchaIf `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`.
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.
affects: >=1.0.0
gotcha`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.
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`.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: opts.parse is not a function
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.
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(...)`.
Cannot find module 'opts'
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.
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.
Argument of type 'string' is not assignable to parameter of type 'boolean | string | number | string[] | undefined'.
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.
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.
Upgrade
Version history
0.1.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources