gpt4 book ai didi

node.js - 如何访问单独文件中的命令选项?

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:28 39 4
gpt4 key购买 nike

我正在使用commander为项目的 index.js 文件中的全局 Node 模块指定一些命令和选项(如 example 中所示)。

我知道我可以使用以下代码轻松检查是否使用了命令:

if (program.peppers) {
console.log('-peppers was used')
}

但是我如何检查其他文件中的这些属性?我已经尝试导出 program 并在其他文件中要求它,但它似乎不起作用。

假设我想检查某个选项是否在与我定义它们的文件不同的文件中使用。我该怎么做?

最佳答案

您可以将解析的程序传递给需要解析的参数的文件/函数,或者您可以导出解析的参数program实例

文件index.js

var program = require('./program');

if (program.peppers) {
console.log('-peppers was used')
}

文件program.js

var program = require('commander');

program
.version('0.0.1')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq-sauce', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);

module.exports = program;

从命令行调用index.js:

> node index.js -p

产生输出

-peppers was used

关于node.js - 如何访问单独文件中的命令选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35059687/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com