Skip to content

Instantly share code, notes, and snippets.

@athoune
Created October 27, 2010 20:57
Show Gist options
  • Save athoune/649973 to your computer and use it in GitHub Desktop.
Save athoune/649973 to your computer and use it in GitHub Desktop.
javascript can be as nice as Erlang for handling cascade callback
MultiPart.prototype.copy = function(writer, callback) {
var mp = this;
var parts = this.parts;
if(this.part != '') { parts.push(this.part); }
parts.push(CRLF + "--" + this.boundary + "--");
parts.reverse();
var BLOCKSIZE = 32*1024;
var readFile = function(fd, total, writer) {
var buffer = new Buffer(BLOCKSIZE);
fs.read(fd, buffer, 0, BLOCKSIZE, null, function(err, bytesRead) {
total -= BLOCKSIZE;
util.log(total);
writer.write(buffer.toString('binary', 0, bytesRead));
if(total > 0) {
readFile(fd, total, writer);
} else {
teardown();
}
});
};
var teardown = function() {
if(parts.length == 0) {
callback();
} else {
var part = parts.pop();
if(part instanceof File) {
var fd = fs.openSync(part.path, 'r');
var total = fs.statSync(part.path).size;
readFile(fd, total, writer);
} else {
writer.write(part, 'utf-8');
teardown();
}
}
};
teardown();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment