in this post, We’ll create nodejs app with localStorage. The localStorage is used to store temporary data into the browser memory. I am using store2 nodejs library for localStorage.
The data in local storage does not have an expiration date. This means that even if the tab or browser window is closed, the data will remain.
Store2
store2 feature-filled and friendly way to take advantage of localStorage and sessionStorage (JSON, namespacing, extensions, etc).
Checkout Other LocalStorage tutorials:
- Local Storage with Angularjs
- How to Use Local Storage with JavaScript
- CRUD Operation Using React Axios
store2 Methods
The main store function can handle set, get, transact, setAll, getAll, each, and clear actions directly:
-
store.set(key, data[, overwrite])
: This method is used to set data under key. -
store.setAll(data[, overwrite]);
: This method is used to set all data. -
store.get(key)
: This method is used to gets localStorage value based on paased key. -
store.getAll([fillObj])
: gets all stored key/data pairs as an object. -
store(key, fn[, alt])
: This method is used to run transaction function on/with data stored under key. -
store.has(key})
: This method return True/false based on key exists in localStorage. -
store.remove(key)
: The removes key and its data, then returns the data or alt, if none. -
store.clear()
: clears all items from storage. -
store.clearAll()
: clears all items from storage except namespace.
How To Integrate localStorage in nodejs
Let’s create a nodejs application and install store 2 cdependecy.Store2 is the most popular library for node.js as a replacement for localStorage and sessionStorage. Apart from the localStorage methods, Tis library provides some additional methods like as transact, setAll, getAll, each, and so on.
Install store2
The following command helps you installing the store2 lib in nodejs application.
//npm npm install store2 //yarn yarn add store2
Now, well import store2 package for localStorage at the to of main.js file.
const store = require("store2");
open main.js
file and paste the below code:
How Store Object in Localstorage
We can set an object to an key using following code:
//Setting store key and data store('Profile', {name: 'Adam', age: 27, salary: 3452});
We can set multiple key and data using store setAll()
method:
store.setAll({name: 'Adam', age: 34})
How To Get Localstorage data
We can use one onf them method to get data which is stored in localStorage.
Get a single key data :
console.log(store('name'))
Get all declared keys :
console.log(store.getAll())