Serializes to disk in the location specified during instantiation
Supports the setting of a quota (default 5MB)
Events. Follows the spec in all ways that make sense for node.js.
However, the spec states that events are NOT supposed to be emitted to the
browser window that took the action that triggered the event in the first place.
Since we don't really have the equivalent of a browser window in node.js, we trigger
events in the current process.
Associative array localStorage['myKey'] = 'myValue' and dot property localStorage.myKey = 'myValue'
syntax if you are in an ES6 supported environment.
Using non-standard _sync() files can be re-read from disk. This is useful if you are using more
than one process to access the same storage location.
Limitations:
When using Associative array or dot property syntax, you cannot use keys that
collide with my "private" properties and methods including keys that start
with "_" like "_init"
If you specify a location that already has files in it when you create an
instance, you might already exceed the quota or might do so sooner than you
expect. This is intentional because we want it to behave like the browser
and persist the storage even after your program is restarted.
unless localStorage? {LocalStorage} = require('../') # require('node-localstorage') for you localStorage = new LocalStorage('./scratch')localStorage.setItem('myFirstKey', 'myFirstValue')console.log(localStorage.getItem('myFirstKey'))# myFirstValuelocalStorage._deleteLocation() # cleans up ./scratch created during doctest
ReactJs
Open or create src/setupTests.js and add these two lines:
// /src/setupTests.jsimport { LocalStorage } from "node-localstorage";global.localStorage = new LocalStorage('./scratch');
JavaScript
if (typeof localStorage === "undefined" || localStorage === null) { var LocalStorage = require('node-localstorage').LocalStorage; localStorage = new LocalStorage('./scratch');}localStorage.setItem('myFirstKey', 'myFirstValue');console.log(localStorage.getItem('myFirstKey'));
Polyfill on Node.js
Polyfil your node.js environment with this as the global localStorage when launching your own code
node -r node-localstorage/register my-code.js
Installation
npm install node-localstorage
Changelog
3.0.5 - 2023-08-05 - Fixed bug with _sync() (thanks @create3000 for the report)
1.3.0 - 2016-04-09 - Possibly backward breaking if you were using experimental syntax Reverted experimental
associative array and dot-property syntax. The API for Proxy changed with node.js v6.x which broke it. Then when
I switched to the new syntax, it broke the EventEmitter functionality. Will restore once I know how to fix that.
1.1.1 - 2016-01-04 - Smarter associative array and dot-property syntax support
1.1.0 - 2016-01-03 - Backward breaking if you used any of the non-standard methods. They are now all preceded with
an underscore. Big upgrade for this version is experimental support for associative array and dot-property syntax.