Skip to content

Instantly share code, notes, and snippets.

@sTiLL-iLL
Last active August 29, 2015 14:12
Show Gist options
  • Save sTiLL-iLL/92cf9b3284a88c01fad1 to your computer and use it in GitHub Desktop.
Save sTiLL-iLL/92cf9b3284a88c01fad1 to your computer and use it in GitHub Desktop.
my nonblocking, threadsafe file writer/appender for nodejs. works great with clustered servers, and child processes that write to shared or static file-stores
//scribbles.js
var fs = require('fs'),
pth = require('path'),
cueMngr = {};
function Scribbles(fileNm) {
this.handle = fileNm;
this.canWrite = false;
this.actionsRoster = [];
};
var scribbles = Scribbles.prototype;
scribbles.action = function (err, dta, actionCue) {
if (err) {
throw err;
}
return actionCue();
}
scribbles.assign = function (func) {
this.action = func;
return this;
}
scribbles.scribble = function (dta, func) {
if (this.canWrite) {
this.actionCue = dta;
if (func) {
this.actionsRoster.push(func);
}
}
else {
this.canWrite = true;
var slf = this,
taskProxy = {};
fs.appendFile(this.handle, dta, function (err) {
function actionCue() {
slf.canWrite = false;
if (slf.actionCue) {
var dta = slf.actionCue;
slf.scribble(dta);
slf.actionCue = null;
}
}
slf.action(err, dta, actionCue);
while (taskProxy = slf.actionsRoster.shift()) {
return taskProxy(err);
}
if (func) {
return func(err);
}
});
}
return this;
};
module.exports = function (fil) {
var nm = pth.resolve(fil);
return (cueMngr[nm] = cueMngr[nm] || new Scribbles(fil));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment