节点命令器选项未定义



我在使用命令时遇到问题:https://github.com/tj/commander.js/

program
    .command('school')
    .arguments("<year>")
    .option("--month <month>", "specify month")
    .parse(process.argv)
    .action(function (year) {
        console.log(`the year is ${year} and the month is ${program.month}`);
    });

我不知道为什么,但即使使用--month 12运行,program.month也是未定义的。

提前谢谢。

尝试使用program.commands[0].month而不是program.month奇怪的是,您竟然访问这样的变量。

也许您可以通过.action参数获得month?我自己对指挥官不是很熟悉。

示例中的month选项已添加到school(子)命令中,而不是添加到程序中。动作处理程序被传递了一个额外的参数,允许您方便地访问它的选项(正如@GiveMeAllYourCats所推测的那样)。

program
  .command('school')
  .arguments("<year>")
  .option("--month <month>", "specify month")
  .action(function (year, options) {
      console.log(`the year is ${year} and the month is ${options.month}`);
  });
program.parse(process.argv);
$ node index.js school --month=3 2020
the year is 2020 and the month is 3

最新更新