var fs = require("fs"); var databases = {}; function jsondb(dbName) { if (databases[dbName]) { return databases[dbName]; } let db = {}; let filename = "./" + dbName + ".db"; // Store context for this database var controller = { load: function () { if (fs.existsSync(filename)) { try { db = JSON.parse(fs.readFileSync(filename)); } catch (err) { console.error("couldn't read " + filename); process.exit(); } } else { db = {}; } }, save: function () { fs.writeFileSync(filename, JSON.stringify(db, false, 0)); }, reset: function () { db = {}; }, put: function (term, serialized) { db[term] = serialized; }, get: function (term) { return db[term]; }, }; databases[dbName] = controller; function exitHandler(options, err) { // if (db) { // fs.writeFileSync(fn, JSON.stringify(db, false, 0)); // } // if (options.cleanup) console.log('clean'); if (err) console.log(err.stack); if (options.exit) process.exit(); } // do something when app is closing process.on("exit", exitHandler.bind(null, { cleanup: true })); // catches ctrl+c event process.on("SIGINT", exitHandler.bind(null, { exit: true })); // catches "kill pid" (for example: nodemon restart) process.on("SIGUSR1", exitHandler.bind(null, { exit: true })); process.on("SIGUSR2", exitHandler.bind(null, { exit: true })); //catches uncaught exceptions process.on("uncaughtException", exitHandler.bind(null, { exit: true })); controller.load(); return controller; } module.exports = jsondb;