Created
October 27, 2010 20:57
-
-
Save athoune/649973 to your computer and use it in GitHub Desktop.
javascript can be as nice as Erlang for handling cascade callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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