Created
October 12, 2016 20:35
-
-
Save bluelovers/a4222795f8069e5ac489009bc0df7248 to your computer and use it in GitHub Desktop.
LokiFsSyncAdapter - A loki persistence adapter which persists using node fs sync module
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
/** | |
* Created by user on 2016/10/13. | |
*/ | |
"use strict"; | |
(function (root, factory) | |
{ | |
if (typeof define === 'function' && define.amd) | |
{ | |
// AMD | |
define([], factory); | |
} | |
else if (typeof exports === 'object') | |
{ | |
// Node, CommonJS-like | |
module.exports = factory(); | |
} | |
else | |
{ | |
// Browser globals (root is window) | |
root.LokiIndexedAdapter = factory(); | |
} | |
}(this, function () | |
{ | |
return (function () | |
{ | |
var Loki = require('lokijs'); | |
function LokiFsSyncAdapter() | |
{ | |
this.fs = require('fs'); | |
} | |
Object.assign(LokiFsSyncAdapter.prototype, Loki.persistenceAdapters.fs.prototype, { | |
loadDatabase: function (dbname, callback) | |
{ | |
var err = null; | |
var stats; | |
try | |
{ | |
stats = this.fs.statSync(dbname); | |
} | |
catch (err) | |
{ | |
} | |
//console.log(err, stats); | |
if (!err && stats && stats.isFile()) | |
{ | |
try | |
{ | |
// readFileSync() is the synchronous alternative to async readFile() which loki normally uses | |
var data = this.fs.readFileSync(dbname, { | |
encoding: 'utf8' | |
} | |
); | |
callback(data); | |
} | |
catch (err) | |
{ | |
callback(new Error(err)); | |
} | |
} | |
else | |
{ | |
callback(null); | |
} | |
}, | |
saveDatabase: function (dbname, dbstring, callback) | |
{ | |
try | |
{ | |
this.fs.writeFileSync(dbname, dbstring); | |
callback(null); | |
} | |
catch (err) | |
{ | |
callback(err); | |
} | |
}, | |
} | |
); | |
//console.log(LokiFsSyncAdapter.prototype.loadDatabase === Loki.persistenceAdapters.fs.prototype.loadDatabase, LokiFsSyncAdapter, LokiFsSyncAdapter.prototype); | |
return LokiFsSyncAdapter; | |
}()); | |
} | |
)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment