【问题标题】:I am trying to run yargs command, and it is not working我正在尝试运行 yargs 命令,但它不起作用
【发布时间】:2019-10-12 07:31:42
【问题描述】:

我在跑步:

node app.js add

我的代码是:

const yargs = require('yargs');
yargs.command({
    command:'add',
    describe:'Adding command',
    handler:function(){
        console.log('Adding notes');
    },
})

但控制台上没有打印任何内容。

【问题讨论】:

  • 你从未调用过 parse 或访问过 argv...
  • @jonrsharpe 你能解释一下为什么我们需要调用argv or parse 来打印处理程序执行吗?我是nodejs 的新手
  • @læran91 因为这些是触发 yargs 实际执行您提供的指令的事情。
  • argv 用于获取传递给节点的参数。在命令行中运行时的 js 进程。这就是你需要它的原因。 ;)

标签: node.js yargs


【解决方案1】:

正如上面评论中提到的@jonrsharpe。

您需要调用parse 函数或访问argv 属性

试试:

const yargs = require('yargs');

yargs
    .command({
        command:'add',
        describe:'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    })
    .parse();

或者

const yargs = require('yargs');

const argv = yargs
    .command({
        command: 'add',
        describe: 'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    })
    .argv;

node index.js add

【讨论】:

  • 你能解释一下为什么我们需要调用argv or parse 来打印处理程序的执行吗?我的意思是执行的背后发生了什么?
  • argv 被设置为一个 javascript getter,这意味着访问这个属性实际上调用了一个方法。
【解决方案2】:

你必须提供 yargs.parse();或 yargs.argv; 在定义所有命令之后。

const yargs = require('yargs');
yargs.command({
    command:'add',
    describe:'Adding command',
    handler:function(){
        console.log('Adding notes');
    },
});

yargs.parse();
//or
yargs.argv;

You can .argv or .parse() specify individually

    yargs.command({
        command:'add',
        describe:'Adding command',
        handler:function(){
            console.log('Adding notes');
        },
    }).parse() or .argv;

【讨论】:

    【解决方案3】:

    如果你有一个命令,这没关系。但是对于多个命令,在定义完所有命令后最后做 yargs.argv。

    const yargs = require('yargs');
     
    const argv = yargs
        .command({
            command: 'add',
            describe: 'Adding command',
            handler: argv => {
                console.log('Adding notes');
            }
        }).argv;
    

    示例解决方案:

    const yargs = require('yargs')
    
    //add command
    yargs.command({
        command: 'add',
        describe: 'Add a new note',
        handler: ()=>{
            console.log("Adding a new note")
        }
    })
    //remove Command
    yargs.command({
        command: 'remove',
        describe: "Remove a Note",
        handler: ()=>{
            console.log("removing note")
        }
    })
    
    yargs.parse()
    

    【讨论】:

      【解决方案4】:

      我也遇到了这个问题,并找到了最新更新节点的解决方案。您需要将文件扩展名从 .js 更改为 .cjs 并且工作正常。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2019-11-13
        • 2021-09-07
        • 1970-01-01
        • 2022-06-11
        相关资源
        最近更新 更多