等待Node.js stream.Readable.pipe()完成

时间:2017-06-06 02:43:37

标签: javascript node.js

我有一个Node.js应用程序,它调用pipe()的{​​{1}}函数。我必须能够在调用函数返回之前等待readableStream完成。

pipe()

从其他函数中调用此函数可以触发多个copyFile一次运行的情况(在这种情况下这是不可取的,即使var copyFile = function(paramSource, paramDestination, paramCallback) { var sourceFile = fs.createReadStream(paramSource); var destinationFile = fs.createWriteStream(paramDestination); sourceFile.on("error", function(error) { return paramCallback(error); }); destinationFile.on("error", function(error) { return paramCallback(error); }); destinationFile.on("close", function() { return paramCallback(null, paramDestination); }); sourceFile.pipe(destinationFile); }; 意味着它)。由此产生的要求是我需要阻止此函数返回,直到destinationFile发出paramCallback事件。目前函数在调用close之后返回,因为它位于函数的末尾,而while循环和布尔标志的任意组合在最后等待完成只会挂起函数。

修改

这是相同的代码,只需简单调用该函数,并将一些文本发送到控制台以跟踪程序流程。

pipe()

这会产生输出:

var copyFile = function(paramSource, paramDestination, paramCallback) {
  var sourceFile = fs.createReadStream(paramSource);
  var destinationFile = fs.createWriteStream(paramDestination);
  sourceFile.on("error", function(error) {
    return paramCallback(error);
  });
  destinationFile.on("error", function(error) {
    return paramCallback(error);
  });
  destinationFile.on("close", function() {
    console.log("close event has been emitted");
    return paramCallback(null, paramDestination);
  });
  console.log("pipe is being called");
  sourceFile.pipe(destinationFile);
  console.log("pipe has been called");
};

copyFile("/home/fatalkeystroke/testing/file1.txt", "/home/fatalkeystroke/testing/file2.txt", function(error, name) {
  if (!error) {
    console.log("callback has been called");
  }
});
console.log("copyFile has been called");

我想要的是:

pipe is being called 
pipe has been called 
copyFile has been called 
close event has been emitted 
callback has been called

0 个答案:

没有答案