[英]NodeJS - Why bother with while loop when reading data off readable stream within the .on('readable') event
这种从可读流(例如请求)读取数据的方式有什么优势:
request.on('readable', function(){
var chunk = null;
while (null !== (chunk = request.read())) {
response.write(chunk);
};
});
vs这种没有while循环的方式? 因为'可读'只会继续射击为什么要打扰while循环?
request.on('readable', function(){
var chunk = request.read();
if(chunk !== null){
response.write(chunk);
}
});
根据API文档:
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
使用res.on('data')事件,您可以在数据准备就绪时获取数据。 这将允许您的程序继续前进并执行其他操作,直到准备好处理下一个数据块(请记住HTTP是通过TCP进行分块)。
使用下面的代码可能会有效,但是为什么在它不必要地占用CPU周期并阻止其他代码执行时(请记住你的Node.js JavaScript代码是单线程的)。 使用事件要好得多,因为它允许JavaScript运行并处理输入/输出而不会不必要地阻塞进程。
request.on('readable', function(){
var chunk = null;
while (null !== (chunk = request.read())) {
response.write(chunk);
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.