我有以下代码:
process.stdin.on('readable', () => {
const input = process.stdin.read();
console.log(input);
});
在教程中,回调似乎在循环中触发,但当我尝试它时,它仅被调用一次,然后退出。为什么会发生这种情况?我的 Node 版本是13.12.0
最佳答案
一旦read
事件触发,它就不会再次触发,直到流到达末尾或直到您调用.read()
并获取null
返回(不再需要读取数据)。一旦你得到null
,那么当有更多数据时它会再次触发。
这就是文档中的示例代码执行此操作的原因:
const readable = getReadableStreamSomehow();
readable.on('readable', function() {
// There is some data to read now.
let data;
while (data = this.read()) {
console.log(data);
}
});
总的来说,这是一种比较困难的使用流的方式。如果您在流动模式下使用它们,如下所示:
process.stdin.on('data', (input) => {
console.log(input);
});
然后,每当数据到达时它就会调用您。
关于javascript - 为什么 Node 的 process.stdin.on ('readable' ) 会触发我的回调一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61468759/