Permalink
Browse files

initial commit

  • Loading branch information...
juliangruber committed Sep 19, 2012
1 parent 1288ab5 commit 1d8dfddac9c8320bb7b9d1dc0793bec6511e3fb0
Showing with 82 additions and 3 deletions.
  1. +17 −3 README.md
  2. +35 −0 index.js
  3. +30 −0 test.js
View
@@ -1,4 +1,18 @@
-json-store
-==========
+JSONStore
+=========
-Simple json db for node
+Simple json store for node. Saves changes on disk immediately and blocking, so only relevant for cli applications and such.
+
+Usage
+-----
+
+```javascript
+var JSONStore = require('json-store');
+var db = JSONStore('./index.json');
+
+db.set('foo', 'bar');
+db.get('foo'); // bar
+
+db.set('obj', {foo: 'bar'});
+db.get('obj').foo // bar
+```
View
@@ -0,0 +1,35 @@
+var fs = require('fs');
+
+function Store(path) {
+ this.path = path;
+ if (!fs.existsSync(path)) fs.writeFileSync(path, JSON.stringify({}));
+ this.Store = require(path);
+}
+
+Store.prototype.get = function(key) {
+ if (!key) return clone(this.Store);
+ if (!this.Store[key]) return;
+ return clone(this.Store[key]);
+}
+
+Store.prototype.set = function(key, value) {
+ this.Store[key] = clone(value);
+ this.save();
+}
+
+Store.prototype.del = function(key) {
+ delete this.Store[key];
+ this.save();
+}
+
+Store.prototype.save = function() {
+ fs.writeFileSync(this.path, JSON.stringify(this.Store));
+}
+
+function clone(data) {
+ return JSON.parse(JSON.stringify(data));
+}
+
+module.exports = function(path) {
+ return new Store(path);
+}
View
30 test.js
@@ -0,0 +1,30 @@
+var JSONStore = require('./index');
+var assert = require('assert');
+var db = JSONStore(__dirname+'/test.json');
+
+process.on('uncaughtException', function(err) {
+ require('fs').unlinkSync(__dirname+'/test.json');
+ throw err;
+});
+
+// return undefined
+assert(typeof db.get('foo') == 'undefined');
+
+// can store values
+db.set('foo', 'bar');
+assert(db.get('foo') == 'bar');
+
+// serializes objects on set
+var obj = {foo: 'bar'};
+db.set('obj', obj);
+obj.foo = 'changed';
+assert(db.get('obj').foo == 'bar');
+
+// serializes objects on get
+var obj = db.get('obj');
+obj.foo = 'changed';
+assert(db.get('obj').foo == 'bar');
+
+console.log('All tests passed');
+
+require('fs').unlinkSync(__dirname+'/test.json');

0 comments on commit 1d8dfdd

Please sign in to comment.