Skip to content

Instantly share code, notes, and snippets.

@pjb3
Created January 25, 2010 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjb3/285544 to your computer and use it in GitHub Desktop.
Save pjb3/285544 to your computer and use it in GitHub Desktop.
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