Compass helpers for node platforms
    Preparing search index...

    Function getCommandParam

    • Type Parameters

      • T = string

      Parameters

      • param: string

        参数名(支持 --param 或 -p 格式)

      • OptionaldefaultValue: T

        默认值

      • options: GetCommandParamOptions = {}

        配置项

        • valueType

          参数的值类型,默认为 'string'

        • validator

          参数的值自定义验证函数,返回 true 或错误信息字符串

        • alias

          参数别名,支持短参数

        • separator

          数组类型的分隔符,默认为 ','

        • required

          是否必需参数

      Returns T

      解析后的参数值

      获取命令行参数

      // 基本用法
      const name = getCommandParam('name', 'default');
      // node script.js --name John

      // 数字类型
      const port = getCommandParam('port', 3000, { valueType: 'number' });
      // node script.js --port 8080

      // 布尔标志
      const debug = getCommandParam('debug', false, { valueType: 'boolean' });
      // node script.js --debug

      // 数组类型
      const files = getCommandParam('files', [], { valueType: 'array' });
      // node script.js --files file1.txt,file2.txt,file3.txt

      // 带验证
      const email = getCommandParam('email', '', {
      validator: (value) => {
      if (typeof value === 'string' && value.includes('@')) {
      return true;
      }
      return 'Email must contain @ symbol';
      }
      });

      // 必需参数
      const apiKey = getCommandParam('api-key', undefined, {
      required: true,
      alias: 'k'
      });
      // node script.js --api-key abc123 或 -k abc123

      // 批量解析
      const config = parseCommandParams({
      host: { defaultValue: 'localhost' },
      port: { valueType: 'number', defaultValue: 3000 },
      ssl: { valueType: 'boolean', defaultValue: false },
      workers: { valueType: 'array', defaultValue: ['main'] }
      });