Introduction
Cache your data with TTL. Using this package in node.js and browser.
Installation
By npm
npm install cache-bucket
Or by yarn
yarn add cache-bucket
Support
Node.js
FileCache and MemoryCache is enable.
Notice that CacheFile will touch a file as storage. The default file path is: ./.filecache
// Based on file; // Based on memory;
Browser
LocalCache and SessionCache and MemoryCache is enable.
Notice that LocalCache is based on localStorage, and SessionCache is based on sessionStorage.
// Based on memory; // Based on localStorage; // Based on sessionStorage;
Methods
get(key: string, defaultValue?: any) => any
Get your cache by key.
If cache is empty, defaultValue will be used. If parameter defaultValue is missing, method will respond null
.
cache; // nullcache; // default-bar
set(key: string, value: any, duration?: number) => void
Set cache data.
The parameter value
type can be string, number, object, array. Cache data will expired after millSeconds when you provide duration.
cache;cache; // Expired after 3 second.cache;
getOrSet(key: string, onEmpty: () => any, duration?: number) => any
Get cache data.
When cache data is missing, method will set data immediately. And then return it.
cache; // bar
add(key: string, value: any, duration?: number) => boolean
Set cache data when key is not exist.
cache; // truecache; // false
remove(key: string) => void
Delete a cache data.
cache;
clearExpired() => void
Clear all expired cache data
cache;
clearAll() => void
Clear all data.
cache;
Advanced
Multiply instances.
; const cache = ; cache;cache; // bar
; const cache = './.new-cachefile'; cache;cache; // bar
Config
You can choose the file you want to put data when Using FileCache. Just creating config file cache-bucekt.json
in project's root directory.