【问题标题】:Why terminal does not show other yargs command?为什么终端不显示其他 yargs 命令?
【发布时间】:2020-04-18 19:48:43
【问题描述】:

当我运行命令node app.js --help 时,终端只显示添加命令,同时我已经定义了三个命令并且它们都有效。当我使用 parse() 方法而不是 argv 时,为什么我会打印 2 次“删除便笺”?

const yargs = require('yargs');


yargs.command({
    command:'add',
    describe:'Adds new note',
    handler:function(){
    console.log('Adding a note')
    }
}).argv;

yargs.command({
    command:'remove',
    describe:'Removes a note',
    handler:function(){
    console.log('Removing a note')
    }
 }).argv;

yargs.command({
    command:'list',
    describe:'Fetches a list of notes',
    handler:function(){
    console.log('Fetching a list')
    }
 }).argv;

Commands:
  app.js add  Adds new note

Options:
  --help     Show help                                                 [boolean]
  --version  Show version number                                       [boolean]
 PS C:\Users\Sanket\Documents\node js\notes-app> 

PS C:\Users\Sanket\Documents\node js\notes-app> node app.js add   

Adding a note
PS C:\Users\Sanket\Documents\node js\notes-app> node app.js remove
Removing a note
Removing a note
PS C:\Users\Sanket\Documents\node js\notes-app> node app.js list  
Fetching a list
PS C:\Users\Sanket\Documents\node js\notes-app> 

【问题讨论】:

    标签: node.js yargs


    【解决方案1】:

    您正在调用.argv,这将在调用help 之前定义其他进程之前停止进程。

    从除您创建的最后一个命令定义之外的所有命令定义中删除 .argv 是解决此问题的最简单方法。

    const yargs = require('yargs');
    
    
    yargs.command({
        command:'add',
        describe:'Adds new note',
        handler:function(){
        console.log('Adding a note')
        }
    });
    
    yargs.command({
        command:'remove',
        describe:'Removes a note',
        handler:function(){
        console.log('Removing a note')
        }
     });
    
    yargs.command({
        command:'list',
        describe:'Fetches a list of notes',
        handler:function(){
        console.log('Fetching a list')
        }
     }).argv;
    

    【讨论】:

    • 成功了,非常感谢。但是argv 做了什么?
    猜你喜欢
    • 2019-08-17
    • 2023-01-11
    • 2022-11-11
    • 1970-01-01
    • 2018-10-09
    • 2020-01-20
    • 2020-04-18
    • 2012-10-01
    • 2019-10-15
    相关资源
    最近更新 更多