亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何編寫命令行參數依賴項?

如何編寫命令行參數依賴項?

陪伴而非守候 2022-07-08 18:24:17
我正在用 NodeJS 編寫一個命令行程序,我目前的想法是我希望將參數解析和邏輯放入index.js其中,然后將實際代碼放入單獨的文件中的函數中。我遇到的問題是如何編寫參數依賴和沖突。出于某種原因cmd,從不包含論點。它僅適用于--help.我究竟做錯了什么?如何在 switch 內部檢查其他參數的存在或不存在?'use strict'const minimist = require('minimist')module.exports = () => {  const args = minimist(process.argv.slice(2))  let cmd = args._[0] || 'help'  if (args.version || args.v) {    console.log("Version 0.1")    exit  }  if (args.help || args.h) {    const help =`Usage: ddparser [OPTION]... [FILE]...Parses DD toml files and updates a webpage accordingly.  --help              Prints this help page  --validate          Validates input file               [requires --input]  --k1-dry-run        Print K1 changes without doing it  [requires --input] [conflicts with --k1-commit]  --k1-commit         Commit k1 changes to website       [requires --k1-token] [conflicts with --k1-dry-run]  --k1-token          K1 token                           [requires --k1-commit]  --input             DD toml file to parse [required]`    console.log(help)  }  // all args below needs content from the toml file to work  // should exit with error if config.toml isn't found  switch (cmd) {    case 'validate':      // error if --input is not specified      // error if any other argument is given      // read config.toml      // read --input toml file      break    case 'k1-dry-run':      // error if --input is not specified      // error if any other argument is given      // run --validate first and error if it fails      // read config.toml      // read --input toml file      break    case 'k1-commit':      // error if --input is not specified      // error if --k1-token is not specified      // run --validate first and error if it fails      // read config.toml      // read --input toml file      break
查看完整描述

1 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

來自minimist

argv._包含所有沒有與之關聯的選項的參數。

除非為該參數名稱設置opts.string或,否則看起來像數字的參數將作為數字返回 。opts.boolean

之后的任何參數'--'都不會被解析,最終會以argv._.

因此,不要調用cmd.js --validate,而是調用它,cmd.js validate否則你可以這樣做:

  let cmd = Object.keys(args).find(item => item !== '_') || 'help'

作為旁注,你正在做:exit而不是 process.exit(),你會得到:

ReferenceError: exit is not defined


查看完整回答
反對 回復 2022-07-08
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號