Skip to content

Instantly share code, notes, and snippets.

@c4milo
Created September 3, 2010 12:27
Show Gist options
  • Save c4milo/563818 to your computer and use it in GitHub Desktop.
Save c4milo/563818 to your computer and use it in GitHub Desktop.
var path = require('path');
var fs = require('fs');
var sys = require('sys');
var EventEmitter = require('events').EventEmitter;
var copy = function copy(src, dst, callback) {
var self = this;
self.on('error', function(err) {
callback(err);
});
self.on('validations', function() {
path.exists(src, function(exists) {
if(!exists) {
self.emit('error', new Error(src + ' does not exists. Nothing to be copied'));
return;
}
fs.stat(src, function(err, stat) {
if(stat.isDirectory()) {
self.emit('error', new Error(src + ' is a directory. It must be a file'));
return;
}
if(src == dst) {
self.emit('error', new Error(src + ' and ' + dst + 'are identical'));
return;
}
//Go!
self.emit('open_infd');
});
});
});
self.on('open_infd', function() {
fs.open(src, 'r', function(err, infd) {
if(err) {
self.emit('error', err);
return;
}
self.emit('open_outfd', infd);
});
});
self.on('open_outfd', function(infd) {
fs.open(dst, 'w', function(err, outfd) {
if(err) {
self.emit('error', err);
return;
}
self.emit('sendfile', infd, outfd);
});
});
self.on('sendfile', function(infd, outfd) {
fs.fstat(infd, function(err, stat) {
if(err) {
self.emit('error', err);
return;
}
fs.sendfile(outfd, infd, 0, stat.size, function() {
self.emit('close_fds', infd, outfd);
callback();
});
});
});
self.on('close_fds', function(infd, outfd) {
fs.close(infd, function(err) {
if(err) {
self.emit('error', err);
}
});
fs.close(outfd, function(err) {
if(err) {
self.emit('error', err);
}
});
});
//Start here
self.emit('validations');
/*fs.open(src, 'r', function(err, infd) {
if(err) callback(err);
fs.fstat(infd, function(err, stat) {
if(err) callback(err);
fs.open(dst, 'w', function(err, outfd) {
if(err) callback(err);
fs.sendfile(outfd, infd, 0, stat.size, function() {
fs.close(infd, function(err) {
if(err) callback(err);
fs.close(outfd, function(err) {
if(err) {
callback(err);
} else {
callback();
}
});
});
});
});
});
});*/
}
sys.inherits(copy, EventEmitter);
fs.copy = function(src, dst, callback) {
return new copy(src, dst, callback);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment