From 9e7d8354ec85d6e03ddec1819a2ab24099b85559 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Tue, 28 Jan 2014 18:22:05 -0700 Subject: [PATCH] Will not reduce objects to '[object Object]' by default. 'strict' option may be used for that. --- README.md | 15 ++++++++++++--- lib/index.js | 17 ++++++++++++----- package.json | 4 ++-- 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 01f2065..116eee0 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,23 @@ Usage ---- var Storage = require('dom-storage') - , localStorage = new Storage('./db.json') // in-file - , sessionStorage = new Storage() // in-memory + + // in-file, doesn't call `String(val)` on values (default) + , localStorage = new Storage('./db.json', { strict: false }) + + // in-memory, does call `String(val)` on values (i.e. `{}` becomes `'[object Object]'` + , sessionStorage = new Storage(null, { strict: true }) + , myValue = { foo: 'bar', baz: 'quux' } ; - localStorage.setItem('myKey', JSON.stringify(myValue)); + localStorage.setItem('myKey', myValue); myValue = localStorage.getItem('myKey'); + // use JSON to stringify / parse when using strict w3c compliance + sessionStorage.setItem('myKey', JSON.stringify(myValue)); + myValue = JSON.parse(localStorage.getItem('myKey')); + API --- diff --git a/lib/index.js b/lib/index.js index 3b72e52..b4c3945 100644 --- a/lib/index.js +++ b/lib/index.js @@ -12,7 +12,8 @@ var fs = require('fs') ; - function Storage(path) { + function Storage(path, opts) { + opts = opts || {}; var db ; @@ -24,6 +25,12 @@ , enumerable: false }); + Object.defineProperty(this, '___priv_strict___', { + value: !!opts.strict + , writable: false + , enumerable: false + }); + try { db = JSON.parse(fs.readFileSync(path)); } catch(e) { @@ -37,13 +44,13 @@ Storage.prototype.getItem = function (key) { if (this.hasOwnProperty(key)) { - return String(this[key]); + return this.___priv_strict___ && String(this[key]) || this[key]; } return null; }; Storage.prototype.setItem = function (key, val) { - this[key] = String(val); + this[key] = this.___priv_strict___ && String(val) || val; this.___save___(); }; @@ -97,8 +104,8 @@ }; Object.defineProperty(Storage, 'create', { - value: function (path) { - return new Storage(path); + value: function (path, opts) { + return new Storage(path, opts); } , writable: false , enumerable: false diff --git a/package.json b/package.json index f24a696..0224354 100644 --- a/package.json +++ b/package.json @@ -2,10 +2,10 @@ "author": "AJ ONeal (http://coolaj86.info)", "name": "dom-storage", "description": "W3C DOM Storage (localStorage and sessionStorage) for Node.JS", - "version": "1.0.2", + "version": "2.0.0", "repository": { "type": "git", - "url": "git://github.com/coolaj86/node-browser-compat.git" + "url": "git://github.com/coolaj86/node-dom-storage.git" }, "engines": { "node": "*"