Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
flat-cache
Advanced tools
The flat-cache package is a simple disk-based key-value store that allows you to set and get data, cache it on disk, and clear the cache when necessary. It is useful for caching results of expensive operations, storing configuration, or any other use case where a simple persistent key-value store is needed.
Caching data to disk
This feature allows you to cache data to disk by setting a key-value pair and then saving the cache. The data can be retrieved later, even after the process is restarted.
const flatCache = require('flat-cache');
let cache = flatCache.load('myCache');
cache.setKey('key', 'value');
cache.save();
Loading cached data from disk
This feature allows you to load previously saved cache from disk and retrieve the value associated with a specific key.
const flatCache = require('flat-cache');
let cache = flatCache.load('myCache');
let value = cache.getKey('key');
Removing a specific key from the cache
This feature allows you to remove a specific key from the cache and then save the updated cache to disk.
const flatCache = require('flat-cache');
let cache = flatCache.load('myCache');
cache.removeKey('key');
cache.save();
Clearing the entire cache
This feature allows you to clear the entire cache and then save the empty cache to disk, effectively resetting it.
const flatCache = require('flat-cache');
let cache = flatCache.load('myCache');
cache.clearAll();
cache.save();
node-cache is an in-memory caching module. It is similar to flat-cache in providing simple key-value storage, but it does not persist the cache to disk by default.
memory-cache is another in-memory key-value store that is similar to flat-cache. It is designed for caching objects in memory and does not include built-in disk persistence.
localforage is a fast and simple storage library for JavaScript. It improves upon flat-cache by providing a more powerful API and support for IndexedDB, WebSQL, and localStorage, which can be used for client-side storage in web applications.
keyv is a simple key-value storage with support for multiple backends, including MongoDB, SQLite, PostgreSQL, and more. Unlike flat-cache, keyv is more versatile due to its support for various storage adapters.
A simple key/value storage using files to persist the data
CacheableMemory
) as the primary storage and then persists the data to diskpersistInterval
setting. Off By DefaultexpirationInterval
to check for expired items in the cache. If it is not set it will do a lazy check on get
or getKey
load
or loadFile
ttl
and lruSize
to manage the cache and persist the datapersistInterval
or calling save()
flatted
to parse and stringify the data by default but can be overridden using serialize
and deserialize
in optionsnpm install flat-cache
import { FlatCache } from 'flat-cache';
const cache = new FlatCache();
cache.setKey('key', 'value');
cache.save(); // Saves the data to disk
lets add it with ttl
, lruSize
, and persistInterval
import { FlatCache } from 'flat-cache';
const cache = new FlatCache({
ttl: 60 * 60 * 1000 , // 1 hour
lruSize: 10000, // 10,000 items
expirationInterval: 5 * 1000 * 60, // 5 minutes
persistInterval: 5 * 1000 * 60, // 5 minutes
});
cache.setKey('key', 'value');
This will save the data to disk every 5 minutes and will remove any data that has not been accessed in 1 hour or if the cache has more than 10,000 items. The expirationInterval
will check every 5 minutes for expired items and evict them. This is replacement to the save()
method with a prune
option as it is no longer needed due to the fact that the in-memory cache handles pruning by ttl
expiration or lruSize
which will keep the most recent there.
here is an example doing load from already existing persisted cache
import { load } from 'flat-cache';
const cache = load('cache1', './cacheAltDirectory');
This will load the cache from the ./cacheAltDirectory
directory with the cache1
id. If it doesnt exist it will not throw an error but will just return an empty cache.
There have been many features added and changes made to the FlatCache
class. Here are the main changes:
FlatCache
is now a class and not a function which you can create instances of or using legacy method load
, loadFile
, or create
FlatCache
now uses CacheableMemory
as the primary storage and then persists the data to diskFlatCache
now uses ttl
and lruSize
to manage the cache and persist the dataFlatCache
now uses expirationInterval
to check for expired items in the cache. If it is not set it will do a lazy check on get
or getKey
getKey
still exists but is now is an alias to get
and will be removed in the futuresetKey
still exists but is now is an alias to set
and will be removed in the futureremoveKey
still exists but is now is an alias to delete
and will be removed in the futureHere is an example of the legacy method load
:
const flatCache = require('flat-cache');
// loads the cache, if one does not exists for the given
// Id a new one will be prepared to be created
const cache = flatCache.load('cacheId');
Now you can use the load
method and ES6 imports:
import { FlatCache } from 'flat-cache';
const cache = new FlatCache();
cache.load('cacheId');
If you do not specify a cacheId
it will default to what was set in FlatCacheOptions
or the default property cacheId
of cache1
and default cacheDir
of ./cache
.
If you want to create a new cache and load from disk if it exists you can use the create
method:
import { create } from 'flat-cache';
const cache = create({ cacheId: 'myCacheId', cacheDir: './mycache', ttl: 60 * 60 * 1000 });
In version 6 we attempted to keep as much as the functionality as possible which includes these functions:
create(options?: FlatCacheOptions)
- Creates a new cache and will load the data from disk if it existscreateFromFile(filePath, options?: FlatCacheOptions)
- Creates a new cache from a fileclearCacheById(cacheId: string, cacheDir?: string)
- Clears the cache by the cacheIdclearAll(cacheDirectory?: string)
- Clears all the cachesttl?
- The time to live for the cache in milliseconds. Default is 0
which means no expirationlruSize?
- The number of items to keep in the cache. Default is 0
which means no limituseClone?
- If true
it will clone the data before returning it. Default is false
expirationInterval?
- The interval to check for expired items in the cache. Default is 0
which means no expirationpersistInterval?
- The interval to save the data to disk. Default is 0
which means no persistencecacheDir?
- The directory to save the cache files. Default is ./cache
cacheId?
- The id of the cache. Default is cache1
serialize?
- The function to parse the data. Default is flatted.parse
deserialize?
- The function to stringify the data. Default is flatted.stringify
cache
- The in-memory cache as a CacheableMemory
instancecacheDir
- The directory to save the cache filescacheId
- The id of the cachecacheFilePath
- The full path to the cache filecacheDirPath
- The full path to the cache directorypersistInterval
- The interval to save the data to diskchangesSinceLastSave
- If there have been changes since the last saveload(cacheId: string, cacheDir?: string)
- Loads the data from diskloadFile(pathToFile: string)
- Loads the data from diskall()
- Gets all the data in the cacheitems()
- Gets all the items in the cachekeys()
- Gets all the keys in the cachesetKey(key: string, value: any, ttl?: string | number)
- (legacy) Sets the key/value pair in the cacheset(key: string, value: any, ttl?: string | number)
- Sets the key/value pair in the cachegetKey<T>(key: string)
- Gets the value for the key or the default valueget<T>(key: string)
- Gets the value for the key or the default valueremoveKey(key: string)
- Removes the key from the cachedelete(key: string)
- Removes the key from the cacheclear()
- Clears the cachesave(force? boolean)
- Saves the data to disk. If force
is true
it will save even if changesSinceLastSave
is false
destroy()
- Destroys the cache and remove filesEvents have been added since v6 to allow for more control and visibility into the cache. Here are the events that are available:
on(event: 'save', listener: () => void)
- Emitted when the cache is savedon(event: 'load', listener: () => void)
- Emitted when the cache is loadedon(event: 'delete', listener: (key: string) => void)
- Emitted when the cache is changedon(event: 'clear', listener: () => void)
- Emitted when the cache is clearedon(event: 'destroy', listener: () => void)
- Emitted when the cache is destroyedon(event: 'error', listener: (error: Error) => void)
- Emitted when there is an errorHere is an example of how to use the error
events:
import { FlatCache, FlatCacheEvents } from 'flat-cache';
const cache = new FlatCache();
cache.on(FlatCacheEvents.error, (error) => {
console.error(error);
});
FlatCacheEvents
is an enum that contains the event names for the on
method. You do not have to use it but makes it easier to know what events are available.
By default flat-cache
uses flatted
to parse and stringify the data. This is to allow for more complex data structures to be saved to disk. If you want to override this you can pass in your own parse
and stringify
functions. Here is an example:
import { FlatCache } from 'flat-cache';
const cache = new FlatCache({
deserialize: JSON.parse,
serialize: JSON.stringify,
});
This will use JSON.parse
and JSON.stringify
to parse and stringify the data. This is useful if you want to use a different library or have a custom way of parsing and stringifying the data.
NOTE: This could cause issues if you are trying to load data that was saved with a different parser or stringifier.
You can contribute by forking the repo and submitting a pull request. Please make sure to add tests and update the documentation. To learn more about how to contribute go to our main README https://github.com/jaredwray/cacheable. This will talk about how to Open a Pull Request
, Ask a Question
, or Post an Issue
.
FAQs
A simple key/value storage using files to persist the data
The npm package flat-cache receives a total of 14,456,916 weekly downloads. As such, flat-cache popularity was classified as popular.
We found that flat-cache demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.