Skip to content

Instantly share code, notes, and snippets.

@josephernest
Created December 22, 2014 22:21
Show Gist options
  • Save josephernest/8bdf46695dc0f1f11898 to your computer and use it in GitHub Desktop.
Save josephernest/8bdf46695dc0f1f11898 to your computer and use it in GitHub Desktop.
Simplest JSON DB possible in node.js
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';
@josephernest
Copy link
Author

Another version (file rewritten only if changes are made): https://gist.github.com/robotlolita/58f3111ab32dec36b790

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