什么是流处理的背压

Dav*_*rez 5 pipe stream node.js backpressure

我开始学习节点和流似乎是你经常使用的东西,在我读过的大部分文档中都提到了处理大文件时的“背压问题”,但我没有找到明确的解释这个问题到底是什么。我也读过使用管道可以帮助解决这个问题,但是管道究竟是如何解决背压问题的?

感谢您提前进行任何解释。

Wag*_*ira 5

背压是指当您写入流的速度比其他进程可以处理/消耗的速度快时,您可以使用管道控制流、暂停和恢复流;这是在 nodejs 中实现背压的示例

var http = require('http'),
    fs = require('fs');

var server = http.createServer(function(request, response) {
  var file = fs.createWriteStream('upload.jpg'),
      fileBytes = request.headers['content-length'],
      uploadedBytes = 0;

  request.on('data', function(chunk) {
    uploadedBytes += chunk.length;
    var progress = (uploadedBytes / fileBytes) * 100;
    response.write('progress: ' + parseInt(progress, 10) + '%\n');

    var bufferOK = file.write(chunk);

    if (!bufferOK) {
      request.pause();
    }
  });

  file.on('drain', function() {
    request.resume();
  });

  request.on('end', function() {
    response.end('upload complete\n');
  });

});

server.listen(8080);
Run Code Online (Sandbox Code Playgroud)

Ben Foster 解决方案 - 来源:https ://gist.github.com/benfoster/9543337