How to intercept callback on fs.createWriteStream in Node.js
node.js
Solution
Those functions do not take callbacks because they synchronously return an object that emits events. In this case, you would listen to `'finish'` on the `WriteStream` to know the copy is done. You'll also want to listen for errors:
var fs = require('fs');
var copy = function(from, to, callback){
var cleanup = function(){
dest.removeListener('finish', finish);
dest.removeListener('error', error);
src.removeListener('error', error);
};
var finish = function(){
cleanup();
callback(null);
};
var error = function(err){
cleanup();
callback(err);
};
var src = fs.createReadStream(from);
var dest = fs.createWriteStream(to);
dest.addListener('finish', finish);
dest.addListener('error', error);
src.addListener('error', error);
src.pipe(dest);
};
That said, you'll probably want to just use a module rather than writing this yourself, probably something like `fs-extra`.
Problem
I'm trying to figure out how to trigger a function when this line of code is completed: ``` fs.createReadStream(req.files.file.path) .pipe(fs.createWriteStream(__dirname+'/public/tmp/'+req.files.file.name)); ``` I think I must be very dense, but is it correct that none of these fs functions carry a callback? How to copy `req.files.file.path` to the destination folder and intercept the completion? http://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options