首页 > 解决方案 > 终端不显示 yargs 的处理程序值

问题描述

我正在学习 node.js,我遇到了第一个问题。安装 yargs 并尝试创建 yargs 命令后,它没有显示在终端中。当我输入node app.js mycommand终端时,它只返回参数数组,而不是我的命令,但如果我输入“node app.js --help”,它会返回每个命令。难道我做错了什么?

const yargs = require('yargs')

 yargs.command({
     command: 'mycommand',
     describe: 'mydesc',
     handler: () => { console.log('some text') } })

我想让我的 console.log 在我输入时显示“一些文本”,'node app.js mycommand'但实际上我只有 args 数组:

{ _: [ 'mycommand' ], '$0': 'app.js' }

标签: node.jsterminalcommandyargs

解决方案


您应该添加.parse()到代码的末尾。就这些。

const yargs = require('yargs')

 yargs.command({
     command: 'mycommand',
     describe: 'mydesc',
     handler: () => { console.log('some text') } }).parse()

如果你有太多这样的命令,而不是为每个命令使用 parse(),只需在你的代码下面输入:

yargs.parse()

或在您的代码下方输入

console.log(yargs.argv)

然而,这也会打印出“argv”(参数向量)。


推荐阅读