Using commander.js 创建一个 CLI,我有这样的语句:
cli.
command('serve').
alias('s').
description('Create a new project').
action((target) => {
console.log("TARGET IS: ", target) ....
无论是否向命令提供值,参数target
记录为值。 我们如何检查target
参数是否为空? 这是当没有值传递给命令时为目标值记录的内容:
TARGET IS: Command {
commands: [],
options: [],
_execs: {},
_allowUnknownOption: false,
_args: [],
_name: 'serve',
_noHelp: false,
parent:
Command {
commands:
[ [Command],
[Command],
[Command],
[Command],
[Command],
[Command],
[Circular],
[Command] ],
options: [ [Option] ],
_execs: {},
_allowUnknownOption: false,
_args: [],
_name: 'sfc',
Command: { [Function: Command] super_: [Function] },
Option: [Function: Option],
_version: '1.0.0',
_versionOptionName: 'version',
_events:
{ 'option:version': [Function],
'command:new': [Function: listener],
'command:n': [Function: listener],
'command:clean': [Function: listener],
'command:c': [Function: listener],
'command:build:main:css': [Function: listener],
'command:bmc': [Function: listener],
'command:build:test:css': [Function: listener],
'command:btc': [Function: listener],
'command:build': [Function: listener],
'command:b': [Function: listener],
'command:test:html': [Function: listener],
'command:t': [Function: listener],
'command:serve': [Function: listener],
'command:s': [Function: listener],
'command:dist': [Function: listener],
'command:d': [Function: listener] },
_eventsCount: 17,
_description: 'SuperflyCSS Command Line Interface',
_argsDescription: undefined,
rawArgs: [ '/usr/bin/node', '/home/ole/.npm-packages/bin/sfc', 'serve' ],
args: [ [Circular] ] },
_alias: 's',
_description: 'Serve project',
_argsDescription: undefined }
以下是用于检查变量是否为 null(或 false(的!
(逻辑 NOT(运算符的可运行代码段。
var nullVar = null;
if(!nullVar){alert("nullVar is null (or false)")}
因此,您可以看到它可以轻松应用于您的案例。
事实证明,如果参数(在本例中是可选的(为 null,则 commander 会用自己的元参数替换它,因此我们无法进行正常的 null 或未定义的检查。 以下是我如何实现检查:
cli.
command('serve').
alias('s').
description('Serve project').
action((target) => {
let serve = null;
if (typeof target === 'string' || target instanceof String) {
serve = target;
}
else {
serve = PLI.target.test.html;
}
有关所有源代码,请参见此处