Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

initial commit

  • Loading branch information...
commit 1d8dfddac9c8320bb7b9d1dc0793bec6511e3fb0 1 parent 1288ab5
Julian Gruber authored September 19, 2012
20  README.md
Source Rendered
... ...
@@ -1,4 +1,18 @@
1  
-json-store
2  
-==========
  1
+JSONStore
  2
+=========
3 3
 
4  
-Simple json db for node
  4
+Simple json store for node. Saves changes on disk immediately and blocking, so only relevant for cli applications and such.
  5
+
  6
+Usage
  7
+-----
  8
+
  9
+```javascript
  10
+var JSONStore = require('json-store');
  11
+var db = JSONStore('./index.json');
  12
+
  13
+db.set('foo', 'bar');
  14
+db.get('foo');                // bar
  15
+
  16
+db.set('obj', {foo: 'bar'});
  17
+db.get('obj').foo             // bar
  18
+```
35  index.js
... ...
@@ -0,0 +1,35 @@
  1
+var fs = require('fs');
  2
+
  3
+function Store(path) {
  4
+  this.path = path;
  5
+  if (!fs.existsSync(path)) fs.writeFileSync(path, JSON.stringify({}));
  6
+  this.Store = require(path);
  7
+}
  8
+
  9
+Store.prototype.get = function(key) {
  10
+  if (!key) return clone(this.Store);
  11
+  if (!this.Store[key]) return;
  12
+  return clone(this.Store[key]);
  13
+}
  14
+
  15
+Store.prototype.set = function(key, value) {
  16
+  this.Store[key] = clone(value);
  17
+  this.save();
  18
+}
  19
+
  20
+Store.prototype.del = function(key) {
  21
+  delete this.Store[key];
  22
+  this.save();
  23
+}
  24
+
  25
+Store.prototype.save = function() {
  26
+  fs.writeFileSync(this.path, JSON.stringify(this.Store));
  27
+}
  28
+
  29
+function clone(data) {
  30
+  return JSON.parse(JSON.stringify(data));
  31
+}
  32
+
  33
+module.exports = function(path) {
  34
+  return new Store(path);
  35
+}
30  test.js
... ...
@@ -0,0 +1,30 @@
  1
+var JSONStore = require('./index');
  2
+var assert = require('assert');
  3
+var db = JSONStore(__dirname+'/test.json');
  4
+
  5
+process.on('uncaughtException', function(err) {
  6
+  require('fs').unlinkSync(__dirname+'/test.json');
  7
+  throw err;
  8
+});
  9
+
  10
+// return undefined
  11
+assert(typeof db.get('foo') == 'undefined');
  12
+
  13
+// can store values
  14
+db.set('foo', 'bar');
  15
+assert(db.get('foo') == 'bar');
  16
+
  17
+// serializes objects on set
  18
+var obj = {foo: 'bar'};
  19
+db.set('obj', obj);
  20
+obj.foo = 'changed';
  21
+assert(db.get('obj').foo == 'bar');
  22
+
  23
+// serializes objects on get
  24
+var obj = db.get('obj');
  25
+obj.foo = 'changed';
  26
+assert(db.get('obj').foo == 'bar');
  27
+
  28
+console.log('All tests passed');
  29
+
  30
+require('fs').unlinkSync(__dirname+'/test.json');

0 notes on commit 1d8dfdd

Please sign in to comment.
Something went wrong with that request. Please try again.