Last active
August 29, 2015 14:12
-
-
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
This file contains hidden or 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
//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