I have a Node.js application which makes a call to the pipe()
function of a readableStream
. I have to be able to wait for pipe()
to complete before the calling function can return however.
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);
};
This function is called from within other functions which can trigger multiple cases of copyFile running at once (which is not desirable in this case, even though paramCallback
would imply it). The resulting requirement is that I need to prevent this function from returning until destinationFile emits a close
event. Currently the function returns after pipe()
is called as it's at the end of the function and any combination of while loops and boolean flags to wait at the end for completion just hangs the function.
EDIT
Here is the same code with a simple call to the function and some text sent to the console to follow the programs flow.
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");
This produces the output:
pipe is being called
pipe has been called
copyFile has been called
close event has been emitted
callback has been called
What I want is:
pipe is being called
pipe has been called
close event has been emitted
callback has been called
copyFile has been called