Skip to content

Instantly share code, notes, and snippets.

@chucknthem
Created March 3, 2010 04:09
Show Gist options
  • Save chucknthem/320302 to your computer and use it in GitHub Desktop.
Save chucknthem/320302 to your computer and use it in GitHub Desktop.
var fs = require("fs");
/**
* Asyncronous file appender in node js that allows you to easily append to a file
* without doing it all once
*/
var Appender = function(filename) {
var queue = Array();
var isOpen = false;
var curObj = this;
/**
* @param text - text to be written.
*/
this.write = function(text) {
//store what needs to be written in a queue
if(text) queue.push(text);
//don't call open again if the queue is still being processed by a previous call to write
if(!isOpen) {
isOpen = true;
//open the file for writing
fs.open(filename, 'a', 33206, function(err, fd) {
if(err) throw err;
var str = queue.shift();
fs.write(fd, str, null , 'utf8', function(err, bytes) {
if(err) throw err;
sys.puts(bytes + ' bytes were written\n' + str);
fs.close(fd, function() {
isOpen = false;
//recursive call to write until queue is empty
if(queue.length > 1) {
curObj.write(null);
}
});
});
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment