问题描述
在我的节点脚本中,我正在等待用户在某个时候按 Enter 键:
In my node script, I am waiting for the user to press enter at some point:
console.log("Press enter to continue...");
await new Promise(function(resolve, reject) {
process.stdin.once("data", function(data) {
resolve();
});
});
脚本运行良好,只有在用户按下 Enter 后才会继续运行.
The script runs fine, and continues only after the user has pressed enter.
但在执行结束时,进程并没有终止.
But at the end of the execution, the process does not terminate.
相反,它似乎只是等待用户输入(即,每次我按 Enter 时都会打印一个换行符).
Instead, it seems to be just pending for user input (i.e., a newline is printed every time I press enter).
我很确定问题与 process.stdin.once
相关,而不是我如何使用 Promise
来强制同步执行.
I'm pretty sure that the problem is related to process.stdin.once
, and not to how I use the Promise
in order to force synchronous execution.
我的脚本中有几个地方必须等待用户按 Enter,因此在解决承诺之前添加 process.stdin.end()
在这里是不可能的(它意味着等待用户按下回车只会工作一次).
I have several places in my script where I have to wait for the user to press enter, so adding process.stdin.end()
before resolving the promise is out of the question here (it means that waiting for the user to press enter will work only once).
我该如何解决这个问题?
How can I resolve this problem?
推荐答案
发生这种情况是因为只要您的 stdin 流打开,节点就会假定您可能正在等待更多数据.以任何方式读取流后,流将自动打开.通知节点您不再需要更多输入的一种简单方法是调用 pause()
.这是一个简单的例子:
This is happening because as long as your stdin stream is open, node assumes you might be waiting for more data. The stream is automatically opened after you read from it in any way. An easy way to inform node you no longer want more input is to call pause()
. Here's a simple example:
async function example() {
console.log("Step 1");
await new Promise(function(resolve, reject) {
process.stdin.once("data", function(data) {
resolve();
});
});
console.log("Step 2");
await new Promise(function(resolve, reject) {
process.stdin.once("data", function(data) {
resolve();
});
});
// more steps...
}
example().then(() => {
console.log("Done");
process.stdin.pause();
});
这篇关于使用“process.stdin.once"时进程永远不会结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!