Created
January 25, 2010 00:24
-
-
Save pjb3/285544 to your computer and use it in GitHub Desktop.
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
posix = require("posix") | |
puts = require("sys").puts | |
events = require("events") | |
exports.fileReader = function (file, options) { | |
// Callers of this function can omit the second argument to accept default options | |
if(!options) { | |
options = {} | |
} | |
var reader = new events.EventEmitter() | |
var filePromise= posix.open(file, process.O_RDONLY, options["mode"] || parseInt("444", 8)) | |
filePromise.addCallback(function(fd) { | |
var buffer_size = options["bufferSize"] || 1024 * 16 | |
var offset = 0 | |
posix.read(fd, buffer_size, offset).addCallback(function(data, bytes_read) { | |
reader.emit("data", data) | |
if(bytes_read == buffer_size) { | |
offset += buffer_size | |
posix.read(fd, buffer_size, offset).addCallback(arguments.callee) | |
} else { | |
posix.close(fd) | |
reader.emit("complete") | |
} | |
}) | |
}) | |
filePromise.addErrback(function() { | |
reader.emit("error", "Unable to read file: " + file) | |
}) | |
return reader | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment