【问题标题】:why yargs.argv causes handler function to invoke为什么 yargs.argv 导致处理函数调用
【发布时间】:2021-06-27 23:44:43
【问题描述】:
const yargs = require("yargs");

yargs.version = "1.0.0";

yargs.command({
  command: "add",
  describe: "do addition ",
  handler: function () {
    console.log("addition complete");
  },
}).argv;

在上面使用 yargs 的代码中,我试图创建一个命令 add 并在使用node . add 运行脚本时,处理函数被执行,我得到了预期的输出

$ 节点。添加
添加完成

但是当相同的代码在没有 .argv 的情况下运行时,输出是空白的并且处理函数没有被执行。 在文档中没有说明 .argv 是什么,它是一个对象或一个函数,以及它是如何工作的。乍一看,它看起来像一个普通的方法调用,但是

当您执行以下操作时
console.log(typeof yargs.argv);

输出是

$ 节点。添加
添加完成
对象

如果 yargs.argv 与任何其他对象一样,那么只需访问它如何以及为什么能够调用函数

有人可以解释实际发生的事情以及我错过了什么。

【问题讨论】:

    标签: javascript node.js args yargs


    【解决方案1】:

    Yargs 使用#getter,这允许javascript 在调用属性时调用函数。

    例子:

    const obj = {
      log: ['a', 'b', 'c'],
      get latest() {
        if (this.log.length === 0) {
          return undefined;
        }
        return this.log[this.log.length - 1];
      }
    };
    
    console.log(obj.latest);
    // expected output: "c"
    

    如果您查看source code,您可以看到当您调用.argv 时,yargs 只是调用.parse()

     const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
     // Legacy yargs.argv interface, it's recommended that you use .parse().
     Object.defineProperty(yargs, 'argv', {
         get: () => {
            return yargs.parse();
          },
         enumerable: true,
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 2019-11-21
      • 1970-01-01
      相关资源
      最近更新 更多