CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-yargs

Command-line argument parsing library for Node.js with commands, options, and validation.

Overview
Eval results
Files

command-system.mddocs/

Command System

Define commands, subcommands, and positional arguments with custom handlers and builders.

Capabilities

Command Definition

Define commands with handlers, builders, and configuration.

/**
 * Define a command with optional subcommands and handlers
 * @param cmd - Command string, definition object, or array
 * @param description - Command description
 * @param builder - Function or object to configure command options
 * @param handler - Function to execute when command is called
 * @param middlewares - Array of middleware functions
 * @param deprecated - Mark command as deprecated
 * @returns YargsInstance for chaining
 */
command(
  cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
  description?: string | boolean,
  builder?: CommandBuilderDefinition | CommandBuilder,
  handler?: CommandHandlerCallback,
  middlewares?: Middleware[],
  deprecated?: boolean
): YargsInstance;

/**
 * Alias for command()
 */
commands(
  cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
  description?: string | boolean,
  builder?: CommandBuilderDefinition | CommandBuilder,
  handler?: CommandHandlerCallback,
  middlewares?: Middleware[],
  deprecated?: boolean
): YargsInstance;

Usage Examples:

// Basic command
yargs()
  .command('serve', 'start the server', {}, (argv) => {
    console.log(`Starting server on port ${argv.port || 3000}`);
  })
  .parse();

// Command with positional arguments
yargs()
  .command('copy <src> <dest>', 'copy a file', (yargs) => {
    return yargs
      .positional('src', {
        describe: 'source file',
        type: 'string'
      })
      .positional('dest', {
        describe: 'destination file',
        type: 'string'
      });
  }, (argv) => {
    console.log(`Copying ${argv.src} to ${argv.dest}`);
  })
  .parse();

// Command with builder object
yargs()
  .command('deploy', 'deploy the application', {
    env: {
      describe: 'environment to deploy to',
      choices: ['staging', 'production'],
      demandOption: true
    }
  }, (argv) => {
    console.log(`Deploying to ${argv.env}`);
  })
  .parse();

// Command definition object
yargs()
  .command({
    command: 'build [target]',
    describe: 'build the project',
    builder: (yargs) => {
      return yargs.positional('target', {
        describe: 'build target',
        choices: ['dev', 'prod'],
        default: 'dev'
      });
    },
    handler: (argv) => {
      console.log(`Building ${argv.target} target`);
    }
  })
  .parse();

Positional Arguments

Define positional arguments within commands.

/**
 * Define positional argument within a command
 * @param key - Positional argument name
 * @param opts - Positional argument configuration
 * @returns YargsInstance for chaining
 */
positional(key: string, opts: PositionalDefinition): YargsInstance;

Usage Examples:

yargs()
  .command('upload <file> [destination]', 'upload a file', (yargs) => {
    return yargs
      .positional('file', {
        describe: 'file to upload',
        type: 'string'
      })
      .positional('destination', {
        describe: 'upload destination',
        type: 'string',
        default: './uploads'
      });
  }, (argv) => {
    console.log(`Uploading ${argv.file} to ${argv.destination}`);
  })
  .parse();

Command Directory Loading

Load commands from directory structure.

/**
 * Load commands from directory
 * @param dir - Directory path containing command files
 * @param opts - Directory loading options
 * @returns YargsInstance for chaining
 */
commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance;

Usage Examples:

// Load all commands from ./commands directory
yargs()
  .commandDir('./commands')
  .parse();

// Load with options
yargs()
  .commandDir('./commands', {
    extensions: ['js', 'ts'],
    recurse: true,
    exclude: /\.test\./
  })
  .parse();

// Command file example (./commands/serve.js):
// module.exports = {
//   command: 'serve [port]',
//   describe: 'start the server',
//   builder: {
//     port: {
//       default: 3000,
//       type: 'number'
//     }
//   },
//   handler: (argv) => {
//     console.log(`Server starting on port ${argv.port}`);
//   }
// };

Default Commands

Define default commands that run when no command is specified.

// Default command using special syntax
yargs()
  .command('$0 [name]', 'default command', (yargs) => {
    return yargs.positional('name', {
      describe: 'name to greet',
      default: 'World'
    });
  }, (argv) => {
    console.log(`Hello, ${argv.name}!`);
  })
  .parse();

// Alternative syntax with *
yargs()
  .command('* [name]', 'default command', (yargs) => {
    return yargs.positional('name', {
      describe: 'name to greet',
      default: 'World'
    });
  }, (argv) => {
    console.log(`Hello, ${argv.name}!`);
  })
  .parse();

Command Aliases

Define command aliases for alternative names.

// Command with aliases
yargs()
  .command(['start', 'run', 's'], 'start the application', {}, (argv) => {
    console.log('Starting application...');
  })
  .parse();

// Or in command definition object
yargs()
  .command({
    command: 'install [packages..]',
    aliases: ['i', 'add'],
    describe: 'install packages',
    handler: (argv) => {
      console.log(`Installing: ${argv.packages.join(', ')}`);
    }
  })
  .parse();

Subcommands

Create hierarchical command structures.

// Git-like subcommand structure
yargs()
  .command('git', 'git commands', (yargs) => {
    return yargs
      .command('clone <repo>', 'clone a repository', {}, (argv) => {
        console.log(`Cloning ${argv.repo}`);
      })
      .command('push [remote]', 'push to remote', {}, (argv) => {
        console.log(`Pushing to ${argv.remote || 'origin'}`);
      })
      .demandCommand(1, 'You need at least one git command');
  })
  .parse();

Command Middleware

Add middleware to commands for argument processing.

yargs()
  .command('process <file>', 'process a file', {}, (argv) => {
    // This handler receives processed argv
    console.log(`Processing ${argv.file} as ${argv.processedType}`);
  }, [
    // Middleware to process file type
    (argv) => {
      argv.processedType = path.extname(argv.file).slice(1);
      return argv;
    }
  ])
  .parse();

Command Recommendations

Enable command recommendations for typos.

/**
 * Enable command recommendations for similar commands
 * @param recommend - Whether to recommend similar commands
 * @returns YargsInstance for chaining
 */
recommendCommands(recommend?: boolean): YargsInstance;

Usage Examples:

yargs()
  .command('start', 'start the server')
  .command('stop', 'stop the server')
  .recommendCommands()
  .parse();

// Running "node app.js strt" would suggest "start"

Types

/**
 * Command handler callback function
 */
type CommandHandlerCallback = (argv: Arguments) => void | Promise<void>;

/**
 * Command builder function
 */
type CommandBuilder = (yargs: YargsInstance) => YargsInstance | Promise<YargsInstance>;

/**
 * Command builder definition object
 */
interface CommandBuilderDefinition {
  [key: string]: OptionDefinition;
}

/**
 * Complete command handler definition
 */
interface CommandHandlerDefinition {
  command?: string | string[];
  aliases?: string | string[];
  describe?: string | boolean;
  desc?: string | boolean;
  description?: string | boolean;
  builder?: CommandBuilder | CommandBuilderDefinition;
  handler: CommandHandlerCallback;
  middlewares?: Middleware[];
  deprecated?: boolean | string;
}

/**
 * Positional argument definition
 */
interface PositionalDefinition {
  alias?: string | string[];
  choices?: string | string[];
  coerce?: (arg: any) => any;
  conflicts?: string | string[];
  default?: any;
  defaultDescription?: string;
  desc?: string;
  describe?: string;
  description?: string;
  implies?: string | number | (string | number)[];
  normalize?: boolean;
  type?: 'boolean' | 'number' | 'string';
}

/**
 * Directory loading options
 */
interface RequireDirectoryOptions {
  extensions?: ReadonlyArray<string>;
  visit?: (commandObject: any, pathToFile: string, filename?: string) => any;
  recurse?: boolean;
  include?: RegExp | ((fileName: string) => boolean);
  exclude?: RegExp | ((fileName: string) => boolean);
}

/**
 * Middleware function
 */
type Middleware = (argv: Arguments) => Arguments | Promise<Arguments>;

Install with Tessl CLI

npx tessl i tessl/npm-yargs

docs

command-system.md

core-parser.md

help-output.md

index.md

option-definition.md

parsing.md

validation.md

tile.json