-
-
Save robotlolita/58f3111ab32dec36b790 to your computer and use it in GitHub Desktop.
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
function Database(file) { | |
this._file = file; | |
this._isDirty = false; | |
this._isLocked = false; | |
this._data = {}; | |
this._saveDelay = 60 * 1000; | |
} | |
Database.prototype = Object.create(EventEmitter.prototype); | |
Database.prototype._store = function() { | |
if (this._isDirty) { | |
this._lock(); | |
fs.writeFile(this._file, JSON.stringify(this._data), function(err) { | |
if (err == null) { | |
this._isDirty = false; | |
} | |
this._unlock(); | |
}.bind(this)) | |
} | |
} | |
Database.prototype._lock = function() { | |
this._isLocked = true; | |
} | |
Database.prototype._unlock = function() { | |
if (this._isLocked) { | |
this._isLocked = false; | |
this.emit('unlock'); | |
} | |
} | |
Database.prototype.load = function(cb) { | |
this._lock(); | |
fs.readFile(this._file, function(err, data) { | |
if (err) cb(err); | |
else { | |
this._data = data; | |
this._unlock(); | |
cb() | |
} | |
}.bind(this)) | |
} | |
Database.prototype._attempt = function(f) { | |
if (this._isLocked) { | |
this.on('unlock', f.bind(this)) | |
} else { | |
f.call(this) | |
} | |
} | |
Database.prototype.set = function(key, value, cb) { | |
this._attempt(function() { | |
this._data[key] = value; | |
this._isDirty = true; | |
setTimeout(this._store.bind(this), this._saveDelay); | |
cb(); | |
}) | |
} | |
Database.prototype.get = function(key, cb) { | |
cb(this._data[key]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you show a little example on how to use it (I'm not so familiar with prototypes)? i.e. just create database, set a value, get a value.