一个nodejs stream诡异的行为, 猜测和事件循环有关系, 求解释?

慕仙森
浏览 628回答 2
2回答

GCT1015

通过I/O读取字符串到缓冲区timers阶段没有callback执行,写入WriteStream,timers阶段检测到callback,执行callback,然鹅ReadStream没数据,pipe没有效果。timers阶段检测到callback,执行callback,ReadStream数据还在,pipe有效果。用process.stdout测试const fs = require('fs')const from = fs.createReadStream('test.txt')from.pipe(process.stdout, {&nbsp; &nbsp; end: false})from.on('end', () => {&nbsp; &nbsp; console.log('end')})setTimeout(() => {&nbsp; &nbsp; console.log('timer callback')&nbsp; &nbsp; from.pipe(process.stdout) //this won't work, if time >= 3}, 3)// setTimeout(() => {//&nbsp; &nbsp; &nbsp;console.log('timer callback')//&nbsp; &nbsp; &nbsp;from.pipe(process.stdout) //this will work, if time < 3// }, 2)

一只萌萌小番薯

默认情况下, 在源流发出时stream.end()在目标Writable流上调用,以便目标不再可写。要禁用此默认行为, 可以将该选项作为传递,从而使目标流保持打开状态:reader.pipe(writer,&nbsp;{&nbsp;end:&nbsp;false&nbsp;});上面说的很清楚了,设置false是保持打开状态,不是你理解的可以一直编辑,也是有时间限制的由于Js是异步处理,所有程序同步执行,写入和settimeout也一样,所以当你设置延迟时长高的时候,是没办法注入进去的。谢谢
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Node.js