0.1.0 • Published 5 years ago
jsonify-storage v0.1.0
jsonify-storage
Introduction
There is a unfriendly case when we use the the native localStorage, such as
localStorage.setItem('foo', { a: 123 })
localStorage.getItem('foo') // => [object Object]
localStorage.setItem('bar', 123)
localStorage.getItem('bar') // => '123'So, jsonify it!
Install
⚠Notice: Can only works in browser environment, other scene need define global variable to mock
Storage.
// In node you have to write like this.
global.localStorage = yourLocalStorage
global.sessionStorage = yourSessionStorageNode:
npm i -D jsonify-storageBrowser:
<script src="./dist/jsonify-storage.umd.min.js"></script>Usage
Import in Node:
// es mode
import { local, session } from 'jsonify-storage'
// or cjs mode
const { local, session } = require('jsonify-storage')In Browser:
const { local, session } = jsonifyStoragelocalmeanslocalStoragesessionmeanssessionStorage
Then you can use it like this:
local.set('foo', { a: 123 })
local.get('foo') // => { a: 123 }
local.get('foo').a === 123 // => true, will retain the type.Payload will be json-stringified before save.
Raw data seems like this:
localStorage.getItem('foo') // => '{"a":123}'If you try to get something can't parsed by JSON or not existed will return null
localStorage.setItem('bar', '我我我')
local.get('bar') // => null
local.get('baz') // => nullOthers apis sames as native Storage, list below.
- setItem -> set
- getItem -> get
- removeItem -> remove
- clear -> clear
- key -> key
- length -> length
More details see API documentation.
0.1.0
5 years ago