Skip to content

Instantly share code, notes, and snippets.

@robotlolita
Created December 22, 2014 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robotlolita/58f3111ab32dec36b790 to your computer and use it in GitHub Desktop.
Save robotlolita/58f3111ab32dec36b790 to your computer and use it in GitHub Desktop.
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]);
}
@josephernest
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment