【问题标题】:Terminal does not show yargs' handler value终端不显示 yargs 的处理程序值
【发布时间】:2019-08-17 15:58:48
【问题描述】:

我正在学习 node.js,我遇到了第一个问题。安装 yargs 并尝试创建 yargs 命令后,它没有显示在终端中。当我在终端中输入node app.js mycommand 时,它只返回参数数组,而不是我的命令,但如果我输入“node app.js --help”,它会返回每个命令。我是不是做错了什么?

const yargs = require('yargs')

 yargs.command({
     command: 'mycommand',
     describe: 'mydesc',
     handler: () => { console.log('some text') } })

我想让我的 console.log 在我输入 'node app.js mycommand' 时显示“一些文本”,但实际上我只有 args 数组:

{ _: [ 'mycommand' ], '$0': 'app.js' }

【问题讨论】:

    标签: node.js terminal command yargs


    【解决方案1】:

    您的代码是只写的。但是您没有显示命令。这就是你什么都看不到的原因。您可以通过两种方式解决此问题。

    1. console.log(yargs.argv)

    2. yargs.parse()

    这些中的任何一个都应在完成代码后添加。

    PS:如果您使用 console.log(yargs.argv) ,argv 对象将与您想要的结果一起打印。

    如果仍然感到困惑,请随时检查以下代码

    const yargs = require('yargs');
    
     yargs.command({
         command: 'mycommand',
         describe: 'mydesc',
         handler: () => { console.log('some text') } 
        });
    
    yargs.parse();
    

    【讨论】:

      【解决方案2】:

      使用yargs.argv;.parse()

      yargs.command({
        command: 'add',
        describe: 'This is add param',
        handler: function() {
          console.log("This is add notes command ");
        }
      });
      yargs.argv;
      

      yargs.command({
        command: 'add',
        describe: 'This is add param',
        handler: function() {
          console.log("This is add notes command ");
        }
      }).parse();
      

      运行它...

      node app.js 添加

      【讨论】:

        【解决方案3】:

        您应该在代码末尾添加.parse()。就是这样。

        const yargs = require('yargs')
        
         yargs.command({
             command: 'mycommand',
             describe: 'mydesc',
             handler: () => { console.log('some text') } }).parse()
        

        如果你有太多这样的命令,而不是为每个命令使用 parse(),只需在你的代码下面输入这个:

        yargs.parse()
        

        或者在你的代码下面输入这个

        console.log(yargs.argv)
        

        不过,这也会打印出“argv”(参数向量)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-08-09
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          • 2021-09-15
          • 2020-02-26
          • 1970-01-01
          相关资源
          最近更新 更多