【问题标题】:command is not adding using yarg npm package命令未使用 yarg npm 包添加
【发布时间】:2019-03-24 06:52:19
【问题描述】:

我正在尝试使用 yarg 添加命令,但是当我运行我的代码时,我的命令没有被添加。

这是我正在尝试的:

const yargs = require('yargs')

//create add command
yargs.command({
    command: 'add',
    describe: 'to add note',
    handler: function() {
        console.log('note has been added')
    } 
})

运行命令:

PS C:\Users\HP\Desktop\node\notes-app> node app.js --help
Options:
  --help     Show help                                                 [boolean]
  --version  Show version number                                       [boolean]

没有添加添加命令。

此外,当我尝试通过将 add 作为参数(即 node app.js add)来运行我的代码时,没有显示任何内容。

我现在该怎么办?

【问题讨论】:

    标签: javascript node.js npm yargs


    【解决方案1】:
    yargs.command({
        command: 'add',
        describe: 'to add note',
        handler: function() {
            console.log('note has been added')
        } 
    }).parse()
    

    如果你不添加 parse(),yargs 将不会执行。如果你有太多的 yargs 命令类型

    yargs.parse()
    

    console.log(yargs.argv)
    

    在下面。

    【讨论】:

      【解决方案2】:

      根据yargs 文档,command 方法需要 4 个参数而不是对象;

      .command(cmd, desc, [builder], [handler])

      所以你的代码应该是这样的(注意,没有更多的括号和对象键):

      //create add command
      yargs.command(
          'add',
          'to add note',
          function() {
              console.log('note has been added')
          } 
      })
      

      如果你没有传递可选的builder 参数,可能应该使用命名参数来处理处理函数(不确定yargs 是如何命名参数的,但我猜它是handler)就像

         ...
         handler = function() {
              console.log('note has been added')
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-20
        • 1970-01-01
        • 2014-02-08
        • 2019-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多