我正在编写旨在从Bash终端执行的Node脚本。它需要几个文件名,然后通过提示向用户询问有关如何处理它们的问题。我正在使用yargs
解析命令行参数,并使用prompt-sync
询问用户问题,而且一切似乎都很好...
除了我像这样通过管道将参数传递给脚本时:
echo "file2.md" | .myscript.js --f1 file1.md
此方法的作用是比较file1.md
和file2.md
,而我正在将pipe-args
与yargs
结合使用以达到目标。但是涉及到提示时,使用管道参数会干扰并阻止其工作。
我已经尝试将其用于脚本之外,并单独使用prompt-sync
和inquirer
进行测试,并将参数传递到脚本中似乎也会影响提示。
所以我现在可以确定它不是特定的提示包。
这是我的提示同步测试(名为prompt-sync-test.js
的文件:]
#!/usr/bin/env node
const prompt = require("prompt-sync")({"sigint": true})
for (var i = 0; i < 5; i++) {
console.log("Going to bring up a prompt")
var result = prompt("This is a test -- enter something >");
console.log("Result", result)
}
运行./prompt-sync.js
运行正常,并每次询问五个问题以打印结果。
但是运行echo hello world | ./prompt-sync-test.js
会为第一个提示打印消息,但是输入的任何内容都会再次重复提示消息,并输入任何先前的答案,就像这样(我在输入y
和n
之间交替进行) ...
$ echo hello world | ./prompt-test.js
Going to bring up a prompt
This is a test -- enter something >y
This is a test -- enter something >y
n
This is a test -- enter something >y
n
y
This is a test -- enter something >y
n
y
n
This is a test -- enter something >y
n
y
n
如何防止这种情况发生,以便我可以将所需的参数传递到脚本中,但仍具有正常的提示行为?
您可以在子shell中使用cat
,如下所示:
(echo "file2.md"; cat) | .myscript.js --f1 file1.md
(echo hello world; cat) | ./prompt-test.js
您也可以添加exec
以减少一个过程:
(echo "file2.md"; exec cat) | .myscript.js --f1 file1.md
(echo hello world; exec cat) | ./prompt-test.js
您也可以将cat
放在外面:
cat <(echo "file2.md") - | .myscript.js --f1 file1.md
cat <(echo hello world) - | ./prompt-test.js