如何在 Node.js 脚本中处理命令行参数

介绍

命令行参数是为命令提供额外输入的一种方式,您可以使用命令行参数为 Node.js 脚本增加灵活性和自定义性。

在本文中,您将了解参数矢量,检测参数旗,处理多个参数和值,以及使用指挥包。

前提条件

要通过这个教程,你需要:

本教程是用Node v16.10.0、npm v7.12.2 和 commander v7.2.0 进行验证的。

使用参数矢量

Node.js 支持通过的参数列表,称为 argument 矢量. 参数矢量是您 Node.js 脚本中的 process.argv 可用的数组。

数组包含已传递到脚本的所有内容,包括 Node.js 可执行和脚本的路径和文件名。

如果你要执行以下命令:

1node example.js -a -b -c

你的参数矢量将包含五个项目:

1[
2  '/usr/bin/node',
3  '/path/to/example.js',
4  '-a',
5  '-b',
6  '-c'
7]

至少在没有任何参数的情况下运行的脚本仍将包含两个项目,即可执行的节点和正在运行的脚本文件。

通常,参数矢量与一个 argument count (argc) 配对,它告诉你有多少参数被传入。

1[label example.js]
2if (process.argv.length === 2) {
3  console.error('Expected at least one argument!');
4  process.exit(1);
5}

此示例代码会检查argv长度2的长度表示只有可执行的节点和脚本文件。

使用论点旗帜

让我们考虑一个示例,其中显示了默认消息. 但是,当一个特定的旗帜存在时,它会显示不同的消息。

1[label example.js]
2if (process.argv[2] && process.argv[2] === '-f') {
3  console.log('Flag is present.');
4} else {
5  console.log('Flag is not present.');
6}

这个脚本检查我们是否在我们的参数矢量中有第三个项目. 索引是2,因为JavaScript中的数组是零索引。

以下是运行脚本没有论点的例子:

1node example.js

所产生的产量:

1[secondary_label Output]
2Flag is not present.

以下是用论点运行脚本的例子:

1node example.js -f

所产生的产量:

1[secondary_label Output]
2Flag is present.

我们不必局限于修改条件控制结构,我们也可以使用已传给脚本的实际值:

1[label example.js]
2const custom = (process.argv[2] || 'Default');
3console.log('Custom: ', custom);

代替基于参数的条件值,此脚本将传入的值(在参数缺失时默认为默认),并将其注入到脚本输出中。

使用价值观的多个论点

我们写了一种接受参数和接受原始值的脚本,我们想要与参数结合使用值的场景如何?

为了让事情变得更复杂一点,让我们也接受多个论点:

 1[label example.js]
 2// Check to see if the -f argument is present
 3const flag = (  
 4  process.argv.indexOf('-f') > -1 ? 'Flag is present.' : 'Flag is not present.'
 5);
 6
 7// Checks for --custom and if it has a value
 8const customIndex = process.argv.indexOf('--custom');
 9let customValue;
10
11if (customIndex > -1) {
12  // Retrieve the value after --custom
13  customValue = process.argv[customIndex + 1];
14}
15
16const custom = (customValue || 'Default');
17
18console.log('Flag:', `${flag}`);
19console.log('Custom:', `${custom}`);

通过使用indexOf,而不是依靠特定的索引值,我们可以搜索参数在参数矢量中的任何地方,无论顺序如何!

以下是运行脚本没有论点的例子:

1node example.js

所产生的产量:

1[secondary_label Output]
2Flag: Flag is not present.
3Custom: Default

以下是用论点运行脚本的例子:

1node example.js -f --custom Override

所产生的产量:

1[secondary_label Output]
2Flag: Flag is present.
3Custom: Override

现在,您的命令行脚本可以接受多个参数和值。

使用指挥

然而,用户可能会尝试使用具有和没有平等符号(-nJaneDoe--name=JohnDoe)的参数,引用字符串以输入空格值(-n "Jane Doe"),甚至有参数交代以提供短语和长语版本。

這就是 commander圖書館可以幫助的地方。

命令器是受欢迎的 Node.js 库,灵感来自同名 Ruby 库。

首先,在您的项目目录中,启动您的项目:

1npm init

然后,安装命令器:

1npm install [email protected]

让我们采取我们之前的例子,并将其输入到使用命令器:

 1[label example-commander.js]
 2const commander = require('commander');
 3
 4commander
 5  .version('1.0.0', '-v, --version')
 6  .usage('[OPTIONS]...')
 7  .option('-f, --flag', 'Detects if the flag is present.')
 8  .option('-c, --custom <value>', 'Overwriting value.', 'Default')
 9  .parse(process.argv);
10
11const options = commander.opts();
12
13const flag = (options.flag ? 'Flag is present.' : 'Flag is not present.');
14
15console.log('Flag:', `${flag}`);
16console.log('Custom:', `${options.custom}`);

命令器通过处理process.argv并将参数和任何相关值作为我们命令器对象的属性来完成所有艰苦的工作。

我们可以轻松地版本我们的脚本,并报告版本号为-v--版本。我们还得到了一些友好的输出,解释了脚本的使用,通过--帮助论点,如果您碰巧通过一个论点,没有定义或缺少一个通过的值,它会引发错误。

结论

在本文中,您了解了参数矢量,检测参数旗,处理多个参数和值,以及使用命令包。

虽然您可以使用自己的命令行参数快速创建脚本,但如果您想要更强大和可维护,您可能需要考虑使用命令器Inquirer.js(LINK0)。

Published At
Categories with 技术
Tagged with
comments powered by Disqus