简体   繁体   English

NodeJS - 在.on('可读')事件中读取可读流数据时,为什么还要使用while循环

[英]NodeJS - Why bother with while loop when reading data off readable stream within the .on('readable') event

What is the advantage of this way of reading data off a readable stream such as a request: 这种从可读流(例如请求)读取数据的方式有什么优势:

request.on('readable', function(){
    var chunk = null;
    while (null !== (chunk = request.read())) {
        response.write(chunk);
    };
});

vs this way without a while loop inside? vs这种没有while循环的方式? Since 'readable' will just keep firing why bother with the while loop? 因为'可读'只会继续射击为什么要打扰while循环?

request.on('readable', function(){
    var chunk = request.read();
    if(chunk !== null){
        response.write(chunk);          
    }
});

As per the API documentation: 根据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);
  });
});

Using the res.on('data') event you get the data when it's ready . 使用res.on('data')事件,您可以在数据准备就绪时获取数据。 This will allow your program to move along and do other things until the next chunk of data is ready to be processed (remember HTTP is over TCP which comes in chunks). 这将允许您的程序继续前进并执行其他操作,直到准备好处理下一个数据块(请记住HTTP是通过TCP进行分块)。

Using the below code might work, but why do that when it's needlessly eating CPU cycles and blocking other code from executing (remember that your Node.js JavaScript code is single-threaded). 使用下面的代码可能会有效,但是为什么在它不必要地占用CPU周期并阻止其他代码执行时(请记住你的Node.js JavaScript代码是单线程的)。 Using events is far better since it allows your JavaScript to run and process input/output without blocking the process needlessly. 使用事件要好得多,因为它允许JavaScript运行并处理输入/输出而不会不必要地阻塞进程。

request.on('readable', function(){
    var chunk = null;
    while (null !== (chunk = request.read())) {
        response.write(chunk);
    };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM