EasyStorage
offers lightweight, JSON storage solution designed for managing simple data structures efficiently. Ideal for small-scale applications or temporary data holding, it automates the persistence of changes to ensure data integrity. Your data is permanently stored on the device and will be restored next time the app is open. The whole database remains in RAM and filesystem.
npm i @silver-zepp/easy-storage
import EasyStorage from "@silver-zepp/easy-storage";
const storage = new EasyStorage();
storage.setKey("name", "John Doe");
console.log(storage.getKey("user")); // "John Doe"
Sets a value for a specified key within the storage. If the key already exists, its value is updated.
key
{string} - The key under which to store the value.value
{any} - The value to store. Can be any type that is serializable to JSON.
// set a simple value
storage.setKey('username', 'johnDoe');
// set an object
storage.setKey('user', { name: 'John', age: 30 });
// updating an existing key
storage.setKey('username', 'johnDoeUpdated');
void
Retrieves the value associated with the specified key from the storage. If the key is not found, returns the default value if provided, or undefined
.
key
{string} - The key whose value to retrieve.defaultValue
{any} - Optional. The default value to return if the key does not exist.
// retrieve an existing key
console.log(storage.getKey('username')); // "johnDoeUpdated"
// retrieve a non-existing key with a default value
console.log(storage.getKey('nonexistent', 'defaultUser')); // "defaultUser"
any
- The value associated with the key, or the default value if the key doesn't exist.
Checks if the specified key exists in the storage.
key
{string} - The key to check for existence.
// check an existing key
console.log(storage.hasKey('username')); // true
// check a non-existing key
console.log(storage.hasKey('nonexistent')); // false
boolean
- true
if the key exists, false
otherwise.
Removes the specified key and its associated value from the storage.
key
{string} - The key to remove.
// remove an existing key
storage.removeKey('username');
void
Returns all keys stored in the storage, optionally stringified.
stringify
{boolean} - Iftrue
, returns the keys as a JSON string; otherwise, returns an array of keys.
// get all keys as an array
console.log(storage.getAllKeys());
// get all keys as a JSON string
console.log(storage.getAllKeys(true));
string | array
- The keys in the storage as a JSON string if stringify
is true, or as an array if stringify
is false.