0

使用command.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 }
4

2 回答 2

1

以下是!(逻辑非)运算符的可运行片段,用于检查变量是否为空(或假)。

   var nullVar = null;
if(!nullVar){alert("nullVar is null (or false)")}

所以你可以看到它可以很容易地应用于你的案例。

于 2018-05-07T22:47:19.737 回答
0

事实证明,如果参数(在这种情况下是可选的)为 null,commander 会用它自己的元参数替换它,所以我们不能进行正常的 null 或 undefined 检查。以下是我实施检查的方式:

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;
    }

所有源代码见这里

于 2018-05-07T22:58:03.047 回答