cache-manager-fs-hash
DefinitelyTyped icon, indicating that this package has TypeScript declarations provided by the separate @types/cache-manager-fs-hash package

3.0.0 • Public • Published

Node Cache Manager store for Filesystem

Build npm package node

Package to cache key-value pairs in JSON files.

Installation

npm install cache-manager-fs-hash

Features

  • Saves anything that is JSON.stringify-able to disk
  • Buffers are saved as well (if they reach a certain size they will be stored to separate files)
  • Works well with the cluster module

Usage example

Here is an example that demonstrates how to use the filesystem cache store.

const { DiskStore } = require('cache-manager-fs-hash');

const diskStore = new DiskStore({
    path: 'diskcache', // path for cached files (default: cache)
    ttl: 60 * 60 * 1000, // time to live in milliseconds 
                         // (default: never expires)
    zip: true, // zip files to save disk space (default: false)
    hash: false, // keys are hashed to generate filenames (default: true)
                 // set to false to use plain keys as filenames
});

(async () => {
    await diskStore.set('key', 'value');
    console.log(await diskStore.get('key')); // "value"

    await diskStore.del('key');
    console.log(await diskStore.get('key')); // undefined

    await diskStore.set('key', 'value', 1000); // with custom TTL
    console.log(await diskStore.ttl('key')); // 999 milliseconds

    // delete stored files
    await diskStore.reset();
})();

Here is an example that demonstrates how to use the store with the node-cache-manager module.

const cacheManager = require('cache-manager');
const { DiskStore } = require('cache-manager-fs-hash');

const diskCache = cacheManager.createCache(new DiskStore({
    path: 'diskcache', // path for cached files
    // ... other options
}));


(async () => {

    await diskCache.set('key', 'value');
    console.log(await diskCache.get('key')); // "value"

    console.log(await getUserCached(5)); // {id: 5, name: '...'}
    console.log(await getUserCached(5)); // {id: 5, name: '...'}

    function getUserCached(userId) {
        return diskCache.wrap(userId, function () {
            return getUser(userId);
        });
    }

    async function getUser(userId) {
        await new Promise(r => setTimeout(r, 100)); // sleep 0.1 seconds
        return {id: userId, name: '...' + Math.random()};
    }

})();

How it works

The library saves each cached item as a separate file under the specified directory. Writes use a .lock file to ensure that multiple instances accessing the same cache file do not interfere with each other.

Tests

npm test

License

cache-manager-fs-hash is licensed under the MIT license.

Package Sidebar

Install

npm i cache-manager-fs-hash

Weekly Downloads

87,400

Version

3.0.0

License

MIT

Unpacked Size

26 kB

Total Files

7

Last publish

Collaborators

  • rolandstarke