Javascript 如何编写命令行参数依赖项?
我正在用NodeJS编写一个命令行程序,我目前的想法是,我希望将参数解析和逻辑放在Javascript 如何编写命令行参数依赖项?,javascript,node.js,ecmascript-6,Javascript,Node.js,Ecmascript 6,我正在用NodeJS编写一个命令行程序,我目前的想法是,我希望将参数解析和逻辑放在index.js中,然后将实际代码放在单独的文件中的函数中 我遇到的问题是如何编写参数依赖项和冲突。由于某些原因,cmd从不包含参数。它仅适用于--help 我做错了什么?如何在开关内部检查是否存在其他参数 'use strict' const minimist = require('minimist') module.exports = () => { const args = minimist(pr
index.js
中,然后将实际代码放在单独的文件中的函数中
我遇到的问题是如何编写参数依赖项和冲突。由于某些原因,cmd
从不包含参数。它仅适用于--help
我做错了什么?如何在开关内部检查是否存在其他参数
'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
case 'k1-token':
// error if --input is not specified
// error if --k1-commit is not specified
// this argument is just a dependency for other args
break
default:
console.log('XXX is not a valid argument.')
break
}
}
发件人:
argv.\u
包含所有没有选项的参数
与他们有联系
看起来像数字的参数将作为数字返回,除非
为该参数名设置了opts.string
或opts.boolean
'-'
之后的任何参数都不会被解析,并将以argv.\u
结束
因此,不要调用cmd.js--validate
,而是将其称为cmd.js validate
,否则您可以执行以下操作:
let cmd = Object.keys(args).find(item => item !== '_') || 'help'
作为旁注,您正在执行:exit
而不是process.exit()
,您将得到:
ReferenceError: exit is not defined