W3C DOM Storage (localStorage and sessionStorage) for node.js
Go to file
AJ ONeal a13644945f
Merge pull request #5 from omphalos/defineProperty
Use Object.defineProperty not __defineGetter__
2018-03-27 22:57:05 -06:00
lib Use Object.defineProperty not __defineGetter__ 2015-10-11 21:27:02 -05:00
tests added whitespace, updated tests for non-strict mode, fixed undefined vs null and string vs number bugs 2014-03-08 14:55:21 -07:00
LICENSE Create LICENSE 2015-02-08 10:30:02 -05:00
README.md Fixed syntax error in README.md 2016-03-03 16:51:10 +01:00
package.json Update license attribute 2015-05-20 22:52:42 -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, ws: '  ' })

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

Options

  • strict - whether to stringify strictly as text [Object object] or as json { foo: bar }.
  • ws - the whitespace to use saving json to disk. Defaults to ' '.

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)

License