Created
December 22, 2014 22:21
-
-
Save josephernest/8bdf46695dc0f1f11898 to your computer and use it in GitHub Desktop.
Simplest JSON DB possible in node.js
This file contains 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
var DBFILENAME = './myDb.json'; | |
var fs = require('fs'); // filesystem access needed | |
var myDb = {}; // the DB will be in RAM | |
try { myDb = JSON.parse(fs.readFileSync(DBFILENAME)); } catch(e) { } // read DB from disk | |
function serialize() { fs.writeFile(DBFILENAME + '.temp', JSON.stringify(myDb), function(err) { if (!err) { fs.rename(DBFILENAME + '.temp', DBFILENAME); } } ); } | |
function serializeSync() { fs.writeFileSync(DBFILENAME + '.temp', JSON.stringify(myDb)); fs.rename(DBFILENAME + '.temp', DBFILENAME); } | |
setInterval(serialize, 60 * 1000); // serialize to disk every minute | |
process.on('exit', serializeSync); process.on('SIGINT', serializeSync); process.on('SIGTERM', serializeSync); // serialize to disk when process terminates | |
/* | |
* DO SOMETHING INTERESTING WITH YOUR DB HERE | |
* | |
* e.g.: | |
*/ | |
myDb['record1'] = 'foo'; | |
myDb['record2'] = 'bar'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another version (file rewritten only if changes are made): https://gist.github.com/robotlolita/58f3111ab32dec36b790