检查命令中的参数是否为空?

时间:2018-05-07 22:19:41

标签: javascript node.js node-commander

使用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 }

2 个答案:

答案 0 :(得分:1)

以下是 !(逻辑NOT)运算符的可运行代码段,用于检查变量是否为null(或false)。



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




因此,您可以看到它可以轻松应用于您的案例。

答案 1 :(得分:0)

事实证明,如果参数(在这种情况下是可选的)为null,则commander用它自己的meta参数替换它,因此我们不能进行正常的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;
    }

对于所有源代码see here