@exa-ai/cache-manager

中文文档
5.5.1-clone发布于 2025/08/01MITTypeScriptCommonJS近 30 天下载 1.1万

Cache module for Node.js

原始使用文档
文档目录14 节
  1. Table of Contents
  2. Features
  3. Installation
  4. Usage Examples
  5. Single Store
  6. Multi-Store
  7. Cache Manager Options
  8. Refresh cache keys in background
  9. Error Handling
  10. Store Engines
  11. Official and updated to last version
  12. Third party
  13. Contribute
  14. License

cache-manager

codecov tests license npm npm

Flexible NodeJS cache module

A cache module for nodejs that allows easy wrapping of functions in cache, tiered caches, and a consistent interface.

Table of Contents

Features

  • Made with Typescript and compatible with ESModules
  • Easy way to wrap any function in cache.
  • Tiered caches -- data gets stored in each cache and fetched from the highest. priority cache(s) first.
  • Use any cache you want, as long as it has the same API.
  • 100% test coverage via vitest.

Installation

pnpm install cache-manager

Usage Examples

Single Store

import { caching } from 'cache-manager';

const memoryCache = await caching('memory', {
  max: 100,
  ttl: 10 * 1000 /*milliseconds*/,
});

const ttl = 5 * 1000; /*milliseconds*/
await memoryCache.set('foo', 'bar', ttl);

console.log(await memoryCache.get('foo'));
// >> "bar"

await memoryCache.del('foo');

console.log(await memoryCache.get('foo'));
// >> undefined

const getUser = (id: string) => new Promise.resolve({ id: id, name: 'Bob' });

const userId = 123;
const key = 'user_' + userId;

console.log(await memoryCache.wrap(key, () => getUser(userId), ttl));
// >> { id: 123, name: 'Bob' }

See unit tests in test/caching.test.ts for more information.

Example setting/getting several keys with mset() and mget()

await memoryCache.store.mset(
  [
    ['foo', 'bar'],
    ['foo2', 'bar2'],
  ],
  ttl,
);

console.log(await memoryCache.store.mget('foo', 'foo2'));
// >> ['bar', 'bar2']

// Delete keys with mdel() passing arguments...
await memoryCache.store.mdel('foo', 'foo2');

Example Express App Usage

Custom Stores

You can use your own custom store by creating one with the same API as the built-in memory stores.

Create single cache store synchronously

As caching() requires async functionality to resolve some stores, this is not well-suited to use for default function/constructor parameters etc.

If you need to create a cache store synchronously, you can instead use createCache():

import { createCache, memoryStore } from 'node-cache-manager';

// Create memory cache synchronously
const memoryCache = createCache(memoryStore(), {
  max: 100,
  ttl: 10 * 1000 /*milliseconds*/,
});

// Default parameter in function
function myService(cache = createCache(memoryStore())) {}

// Default parameter in class constructor
const DEFAULT_CACHE = createCache(memoryStore(), { ttl: 60 * 1000 });
// ...
class MyService {
  constructor(private cache = DEFAULT_CACHE) {}
}

Multi-Store

import { multiCaching } from 'cache-manager';

const multiCache = multiCaching([memoryCache, someOtherCache]);
const userId2 = 456;
const key2 = 'user_' + userId;
const ttl = 5;

// Sets in all caches.
await multiCache.set('foo2', 'bar2', ttl);

// Fetches from highest priority cache that has the key.
console.log(await multiCache.get('foo2'));
// >> "bar2"

// Delete from all caches
await multiCache.del('foo2');

// Sets multiple keys in all caches.
// You can pass as many key, value tuples as you want
await multiCache.mset(
  [
    ['foo', 'bar'],
    ['foo2', 'bar2'],
  ],
  ttl
);

// mget() fetches from highest priority cache.
// If the first cache does not return all the keys,
// the next cache is fetched with the keys that were not found.
// This is done recursively until either:
// - all have been found
// - all caches has been fetched
console.log(await multiCache.mget('key', 'key2'));
// >> ['bar', 'bar2']

// Delete keys with mdel() passing arguments...
await multiCache.mdel('foo', 'foo2');

See unit tests in test/multi-caching.test.ts for more information.

Cache Manager Options

The caching and multiCaching functions accept an options object as the second parameter. The following options are available:

  • max: The maximum number of items that can be stored in the cache. If the cache is full, the least recently used item is removed.
  • ttl: The time to live in milliseconds. This is the maximum amount of time that an item can be in the cache before it is removed.
  • shouldCloneBeforeSet: If true, the value will be cloned before being set in the cache. This is set to true by default.
import { caching } from 'cache-manager';

const memoryCache = await caching('memory', {
  max: 100,
  ttl: 10 * 1000 /*milliseconds*/,
  shouldCloneBeforeSet: false, // this is set true by default (optional)
});

Refresh cache keys in background

Both the caching and multicaching modules support a mechanism to refresh expiring cache keys in background when using the wrap function.
This is done by adding a refreshThreshold attribute while creating the caching store or passing it to the wrap function.

If refreshThreshold is set and after retrieving a value from cache the TTL will be checked.
If the remaining TTL is less than refreshThreshold, the system will update the value asynchronously,
following same rules as standard fetching. In the meantime, the system will return the old value until expiration.

NOTES:

  • In case of multicaching, the store that will be checked for refresh is the one where the key will be found first (highest priority).
  • If the threshold is low and the worker function is slow, the key may expire and you may encounter a racing condition with updating values.
  • The background refresh mechanism currently does not support providing multiple keys to wrap function.
  • If no ttl is set for the key, the refresh mechanism will not be triggered. For redis, the ttl is set to -1 by default.

For example, pass the refreshThreshold to caching like this:

const memoryCache = await caching('memory', {
  max: 100,
  ttl: 10 * 1000 /*milliseconds*/,
  refreshThreshold: 3 * 1000 /*milliseconds*/,
  
  /* optional, but if not set, background refresh error will be an unhandled
   * promise rejection, which might crash your node process */
  onBackgroundRefreshError: (error) => { /* log or otherwise handle error */ }
});

When a value will be retrieved from Redis with a TTL minor than 3sec, the value will be updated in the background.

Error Handling

Cache Manager now does not throw errors by default. Instead, all errors are evented through the error event. Here is an example on how to use it:

const memoryCache = await caching('memory', {
  max: 100,
  ttl: 10 * 1000 /*milliseconds*/,
});
memoryCache.on('error', (error) => {
  console.error('Cache error:', error);
});

Store Engines

Official and updated to last version

Third party

Contribute

If you would like to contribute to the project, please read how to contribute here CONTRIBUTING.md.

License

cache-manager is licensed under the MIT license.

版本与发布记录

@exa-ai/cache-manager 共发布 1 个版本,首次发布于 2025/08/01;过去 12 个月发布了 0 个版本。

版本发布日期距今
5.5.1-clonelatest2025/08/011.3 年前

关于 @exa-ai/cache-manager 的常见问题

@exa-ai/cache-manager 是什么?

Cache module for Node.js

如何安装 @exa-ai/cache-manager?

在项目目录运行 npm install @exa-ai/cache-manager,或使用 pnpm add / yarn add / bun add。

@exa-ai/cache-manager 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@exa-ai/cache-manager 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@exa-ai/cache-manager 可以商用吗?

@exa-ai/cache-manager 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@exa-ai/cache-manager 的下载量有多少?

根据 npm 官方下载统计,@exa-ai/cache-manager 在 2026/10/14 – 2026/11/12 这 30 天内被下载 10,997 次,日均约 367 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@exa-ai/cache-manager 还在维护吗?

最新版本 5.5.1-clone 发布于 2025/08/01(1.3 年前);至今共发布 1 个版本,其中过去 12 个月发布了 0 个;首次发布于 2025/08/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。