-
-
Save jloiola/cc4036311b249f4e02ba3af1475c8b30 to your computer and use it in GitHub Desktop.
NodeJS File object
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
var File = { | |
open: function (path, mode) { | |
var fd, queue, enc; | |
enc = 'utf8'; | |
queue = []; | |
// This is called after each step in the queue finishes, when the queue is empty, then we close the file descriptor. | |
function run_next() { | |
if (queue.length > 0) { | |
node.debug("pulling from queue"); | |
(queue.shift())(); | |
} else { | |
node.debug("done, closing"); | |
node.fs.close(fd); | |
} | |
} | |
// generator is a function that returns an array of [fn, arg1, arg2, ...] | |
function enqueue(generator) { | |
var promise, args, fn; | |
promise = new node.Promise(); | |
queue.push(function () { | |
args = generator(); | |
fn = args.shift(); | |
node.debug(fn + JSON.stringify(args)); | |
fn.apply(this, args).addCallback(function () { | |
node.debug("action returned " + Array.prototype.slice.call(arguments)); | |
promise.emitSuccess.apply(promise, arguments); | |
run_next(); | |
}); | |
}); | |
return promise; | |
} | |
// Kick off the process | |
node.fs.open(path, mode, 0644).addCallback(function (file_descriptor) { | |
fd = file_descriptor; | |
node.debug("File opened, starting queue: " + fd); | |
run_next(); | |
}); | |
// Return an object with public facing methods | |
return { | |
write: function (message) { | |
node.debug("enqueue write command"); | |
return enqueue(function () { | |
node.debug("write generated: " + fd) | |
return [node.fs.write, fd, message, 0, enc]; | |
}); | |
} | |
}; | |
} | |
} | |
// This should open the file, then write to the file, then close the file, all as chained events | |
// and automatically. | |
var f = File.open("test.txt", "w"); | |
f.write("Hello World\n"); | |
f.write("Hello World2\n"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment