Light weight persistent cache backed by node-cache. It persists in-memory cache periodically on disk while also saving every write command in an append-only manner to guarantee minimal data loss during application restarts.
npm i persistent-node-cache
import { PersistentNodeCache } from "persistent-node-cache";
const cache = new PersistentNodeCache("mycache", 1000);
cacheName
:string
(required) the name of the cache. Used for recovering/restoring cache from disk.period
:number
(default:1 second
) interval at which cache backup is saveddir
:string
(default:home dir of user
) directory where backup files will be createdopts
:object
standard options ofnode-cache
packageserializer
: CacheSerializer (default:JSON serializer
) custom serializer for persisting data on disk
type CacheSerializer = {
serialize: Function;
deserialize: Function;
}
All cache operations are similar to those of node-cache package since it's an extension of implementation of node-cache. Please refer to node-cache docs for an extensive list of all operations supported.
cache.set(key, val, [ttl])
Sets a key-value pair. Defining ttl
is optional.
cache.set("mykey", "myval", 1000); //true
Get a key-value pair.
cache.get("mykey"); //myval
Delete a key from cache. Returns the number of entries deleted.
cache.del("mykey"); //1
The cache is restored automatically when the cache is initialized (again). Parameter is cacheName
should be passed. dir
will have to be passed if the cache was created specifying a custom directory.
const cache = new PersistentNodeCache("mycache");
cache.get("mykey"); //myval
The cacheName
field should be passed to tell which cache to restore. If dir
field was passed during cache initialization previously, it should be passed during recovery as well to locate the backup files.
const cache = new PersistentNodeCache("mycache");
cache.recover();
cache.get("mykey"); //myval
import { PersistentNodeCache, CacheSerializer } from "persistent-node-cache";
const customSerializer: CacheSerializer = {
serialize: (item: any) => {
return Buffer.from(Buffer.from(JSON.stringify(item)).toString('base64') + '\n');
},
deserialize: (bf: Buffer) => {
return JSON.parse(Buffer.from(bf.toString().trim(), 'base64').toString());
}
};
const cache = new PersistentNodeCache("mycache", 0, '', {}, customSerializer);
Benchmark figures for get/set operations (on an Apple M2, 8 GB RAM system)
get | set | |
---|---|---|
persistent-node-cache |
21,074,363 ops/sec | 623,668 ops/sec |
node-cache |
15,939,686 ops/sec | 8,862,257 ops/sec |
persistent-cache |
8,670,967 ops/sec | 550 ops/sec |