繁体   English   中英

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

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

我在跑步:

node app.js add

我的代码是:

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

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

正如@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

你必须提供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;

如果您只有一个命令,这没问题。 但是对于多条命令,在定义完所有命令后,最后再做 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()

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

暂无
暂无

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

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