빠른 참조

Yargs CLI 파서 치트시트

Node.js용 명령줄 파서 Yargs 빠른 참조 가이드: 인자 파싱, 옵션 설정, 명령어 등록, 플래그 카운팅 및 도움말 생성을 정리합니다.

· 게시일

Yargs는 인자를 파싱하고 깔끔한 사용자 인터페이스를 생성하여 대화형 명령줄 도구를 쉽게 구축하도록 돕습니다.

기본 사용법

const argv = require('yargs').argv;

argv._         // Array of positional arguments: [ ... ]
argv.$0        // Executable name: "node bin/mybin"
argv.verbose   // Boolean / string flag value: --verbose

버전 및 도움말 출력

const argv = require('yargs')
  // Version configuration
  .alias('v', 'version')
  .version(function() { return require('../package').version; })
  .describe('v', 'show version information')

  // Help configuration
  .alias('h', 'help')
  .help('help')
  .usage('Usage: $0 -x [num]')
  .showHelpOnFail(false, "Specify --help for available options")

옵션 구성

  .option('f', {
    alias: 'file',
    describe: 'Path to target file',
    type: 'string', /* 'array' | 'boolean' | 'string' */
    nargs: 1,
    demand: true,
    demand: 'file is required',
    default: '/etc/passwd'
    // also supports: count: true, requiresArg: true
  })

  .options({
    f: { /* option hash */ }
  })

명령어 및 예제

  .example('$0 -f config.json', 'Run with configuration file')
  .epilog('Copyright 2026')
  .command('start', 'Start the server application')

플래그 카운팅 및 누적

  .count('verbose')

// Passing -vvv results in:
argv.verbose // => 3

엄격 모드 (Strict Mode)

  .strict()

프로그래밍 방식 메서드

yargs.showHelp()
const helpText = yargs.help() // => string output

관련 주제