为了账号安全,请及时绑定邮箱和手机立即绑定

如何编写命令行参数依赖项?

如何编写命令行参数依赖项?

陪伴而非守候 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 关注
  • 174 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号