简体   繁体   English

我正在尝试运行 yargs 命令,但它不起作用

[英]I am trying to run yargs command, and it is not working

I am running:我在跑步:

node app.js add

And my code is:我的代码是:

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

But nothing printed on the console.但是控制台上没有打印任何内容。

As @jonrsharpe mentioned in the comment above.正如@jonrsharpe 在上面的评论中提到的那样。

You need to either call parse function or access argv property您需要调用parse函数或访问argv属性

Try:尝试:

const yargs = require('yargs');

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

Or或者

const yargs = require('yargs');

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

node index.js add

You have to provide the yargs.parse();你必须提供yargs.parse(); or yargs.argv;或 yargs.argv; after defining all the commands.定义所有命令后。

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

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

or或者

You can .argv or .parse() specify individually

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

This is okay if you have one command.如果您只有一个命令,这没问题。 But for multiple commands, do yargs.argv at last after defining all commands.但是对于多条命令,在定义完所有命令后,最后再做 yargs.argv。

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

Example solution:示例解决方案:

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()

I also face this issue and find the solution with latest update of node.我也遇到了这个问题,并找到了 node.js 最新更新的解决方案。 You need to change file extension from .js to .cjs and its working fine.您需要将文件扩展名从 .js 更改为 .cjs 并且它工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM