W3C DOM Storage (localStorage and sessionStorage) for node.js
Go to file
AJ ONeal c617241c52 Merge branch 'master' of github.com:coolaj86/node-dom-storage 2014-01-28 18:22:18 -07:00
lib Will not reduce objects to '[object Object]' by default. 'strict' option may be used for that. 2014-01-28 18:22:05 -07:00
tests test that we don't return prototype methods 2013-01-26 02:24:05 -07:00
README.md Merge branch 'master' of github.com:coolaj86/node-dom-storage 2014-01-28 18:22:18 -07:00
package.json Will not reduce objects to '[object Object]' by default. 'strict' option may be used for that. 2014-01-28 18:22:05 -07:00

README.md

sessionStorage & localStorage for NodeJS

An inefficient, but as W3C-compliant as possible using only pure JavaScript, DOMStorage implementation.

Purpose

This is meant for the purpose of being able to run unit-tests and such for browser-y modules in node.

Usage

var Storage = require('dom-storage')

    // 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', 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

  • getItem(key)
  • setItem(key, value)
  • removeItem(key)
  • clear()
  • key(n)
  • length

Tests

0 === localStorage.length;
null === localStorage.getItem('doesn't exist');
undefined === localStorage['doesn't exist'];

localStorage.setItem('myItem');
"undefined" === localStorage.getItem('myItem');
1 === localStorage.length;

localStorage.setItem('myItem', 0);
"0" === localStorage.getItem('myItem');

localStorage.removeItem('myItem', 0);
0 === localStorage.length;

localStorage.clear();
0 === localStorage.length;

Notes

  • db is read in synchronously
  • No callback when db is saved
  • Doesn't not emit Storage events (not sure how to do)