W3C DOM Storage (localStorage and sessionStorage) for node.js
Go to file
AJ ONeal 09b007e656
Merge pull request #3 from pdehaan/patch-1
Update license attribute
2018-03-27 22:56:50 -06:00
lib 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
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