UNPKG

2.76 kBMarkdownView Raw
1# flat-cache
2> A stupidly simple key/value storage using files to persist the data
3
4[![NPM Version](http://img.shields.io/npm/v/flat-cache.svg?style=flat)](https://npmjs.org/package/flat-cache)
5[![Build Status](https://api.travis-ci.org/royriojas/flat-cache.svg?branch=master)](https://travis-ci.org/royriojas/flat-cache)
6
7## install
8
9```bash
10npm i --save flat-cache
11```
12
13## Usage
14
15```js
16var flatCache = require('flat-cache')
17// loads the cache, if one does not exists for the given
18// Id a new one will be prepared to be created
19var cache = flatCache.load('cacheId');
20
21// sets a key on the cache
22cache.setKey('key', { foo: 'var' });
23
24// get a key from the cache
25cache.getKey('key') // { foo: 'var' }
26
27// fetch the entire persisted object
28cache.all() // { 'key': { foo: 'var' } }
29
30// remove a key
31cache.removeKey('key'); // removes a key from the cache
32
33// save it to disk
34cache.save(); // very important, if you don't save no changes will be persisted.
35// cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys
36
37// loads the cache from a given directory, if one does
38// not exists for the given Id a new one will be prepared to be created
39var cache = flatCache.load('cacheId', path.resolve('./path/to/folder'));
40
41// The following methods are useful to clear the cache
42// delete a given cache
43flatCache.clearCacheById('cacheId') // removes the cacheId document if one exists.
44
45// delete all cache
46flatCache.clearAll(); // remove the cache directory
47```
48
49## Motivation for this module
50
51I needed a super simple and dumb **in-memory cache** with optional disk persistance in order to make
52a script that will beutify files with `esformatter` only execute on the files that were changed since the last run.
53To make that possible we need to store the `fileSize` and `modificationTime` of the files. So a simple `key/value`
54storage was needed and Bam! this module was born.
55
56## Important notes
57- If no directory is especified when the `load` method is called, a folder named `.cache` will be created
58 inside the module directory when `cache.save` is called. If you're committing your `node_modules` to any vcs, you
59 might want to ignore the default `.cache` folder, or specify a custom directory.
60- The values set on the keys of the cache should be `stringify-able` ones, meaning no circular references
61- All the changes to the cache state are done to memory
62- I could have used a timer or `Object.observe` to deliver the changes to disk, but I wanted to keep this module
63 intentionally dumb and simple
64- Non visited keys are removed when `cache.save()` is called. If this is not desired, you can pass `true` to the save call
65 like: `cache.save( true /* noPrune */ )`.
66
67## License
68
69MIT
70
71## Changelog
72
73[changelog](./changelog.md)