jaredwray / flat-cache

A stupidly simple key/value storage using files to persist the data
MIT License
165 stars 30 forks source link

flat-cache

A stupidly simple key/value storage using files to persist the data

NPM Version tests codecov npm

install

npm i --save flat-cache

Usage

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');

// sets a key on the cache
cache.setKey('key', { foo: 'var' });

// get a key from the cache
cache.getKey('key'); // { foo: 'var' }

// fetch the entire persisted object
cache.all(); // { 'key': { foo: 'var' } }

// remove a key
cache.removeKey('key'); // removes a key from the cache

// save it to disk
cache.save(); // very important, if you don't save no changes will be persisted.
// cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys

// loads the cache from a given directory, if one does
// not exists for the given Id a new one will be prepared to be created
const cache = flatCache.load('cacheId', path.resolve('./path/to/folder'));

// The following methods are useful to clear the cache
// delete a given cache
flatCache.clearCacheById('cacheId'); // removes the cacheId document if one exists.

// delete all cache
flatCache.clearAll(); // remove the cache directory

Motivation for this module

I needed a super simple and dumb in-memory cache with optional disk persistance in order to make a script that will beutify files with esformatter only execute on the files that were changed since the last run. To make that possible we need to store the fileSize and modificationTime of the files. So a simple key/value storage was needed and Bam! this module was born.

Important notes

License

MIT © Jared Wray