zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[Node.js]15. Level 3: Solving Backpressure

JSNode 15 level
2023-09-14 08:59:22 时间

Even though we know pipe does all the heavy lifting for us when dealing with backpressure, it's still a good idea for us to know about what is going on. Below, we are copying a file using Readable and Writeable streams.

Update the code to account for backpressure, without using pipe.

var fs = require('fs');

var file = fs.createReadStream("icon.png");
var newFile = fs.createWriteStream("icon-new.png");

file.on('data', function(chunk) {
  newFile.write(chunk);
});

file.on('end', function() {
  newFile.end();
});

 

Answer: 

var fs = require('fs');

var file = fs.createReadStream("icon.png");
var newFile = fs.createWriteStream("icon-new.png");

file.on('data', function(chunk) {
  
  var buffer = newFile.write(chunk);
  if(!buffer){
      file.pause();
  }
});

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

file.on('end', function() {
  newFile.end();
});