Skip to content

Instantly share code, notes, and snippets.

@tjoen
Forked from josephernest/simplestdb.js
Created November 14, 2017 23:19
Show Gist options
  • Save tjoen/80d34cb17c65e14f2ee3ecaab46e1498 to your computer and use it in GitHub Desktop.
Save tjoen/80d34cb17c65e14f2ee3ecaab46e1498 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';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment