如何使用node js在终端中编写函数的参数

How to write the argument of a function in the terminal with node js

我正在使用此代码连接到 mailchimp API,获取成员列表并将他们的所有电子邮件地址放入一个数组中:

var mailchimpMarketing = require("@mailchimp/mailchimp_marketing");

mailchimpMarketing.setConfig({
  apiKey: "MY API KEY",
  server: "MY SERVER",
});


async function getArrayEmailMembersFromMailchimpListID(listID){
  const response = await mailchimpMarketing.lists.getListMembersInfo(listID);
  const emailsMailchimp = response.members.map(member => member.email_address);
  console.log(emailsMailchimp)
  return emailsMailchimp;
}
getArrayEmailMembersFromMailchimpListID("MY LIST ID")

我的问题是我想在我的终端中写入列表 ID "MY LIST ID",而不是在我启动脚本时在我的代码中写入。类似的东西:

$node test.js MyListID

而不是

$node test.js

但是我不知道怎么做。

我认为 process.argvminimist 是可行的,但我不明白它们是如何工作的。有人可以向我解释一下吗?或者他们还有其他可能性吗?

来自Node-JSv8.xdocumentation:

The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched. The first element will be process.execPath. See process.argv0 if access to the original value of argv[0] is needed. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command line arguments.

所以在你的情况下你可以简单地做:

getArrayEmailMembersFromMailchimpListID(process.argv[2])

当然你应该为此添加一些error-handling以使其更健壮。