这六个 npm 包都用于在 JavaScript/Node.js 应用中实现缓存功能,但各自定位和适用场景不同。lru-cache 是纯粹的内存 LRU 缓存实现,性能最优但功能单一。node-cache 和 memory-cache 提供简单的键值存储,支持过期时间。cache-manager 是缓存抽象层,支持多种存储后端。cacheable-request 自动缓存 HTTP 请求,基于标准 HTTP 缓存头。axios-cache-adapter 专为 axios 设计,拦截请求实现缓存。选择时需考虑:是否需要 HTTP 语义缓存、是否需要多存储后端、是否绑定特定 HTTP 客户端、以及性能要求。
在构建高性能 JavaScript 应用时,缓存是减少重复计算、降低网络请求、提升响应速度的关键手段。这六个包代表了不同的缓存思路:有的专注内存数据结构(lru-cache),有的提供存储抽象(cache-manager),有的自动处理 HTTP 缓存语义(cacheable-request),有的绑定特定 HTTP 客户端(axios-cache-adapter)。让我们从实际工程角度深入对比。
lru-cache 是纯粹的内存数据结构实现,专注于 LRU(最近最少使用)淘汰算法。
import { LRUCache } from 'lru-cache';
const cache = new LRUCache({
max: 500,
ttl: 1000 * 60 * 5 // 5 分钟过期
});
cache.set('key', 'value');
const value = cache.get('key');
node-cache 提供简单的键值存储,支持过期时间和事件钩子。
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 300 });
cache.set('key', 'value');
const value = cache.get('key');
cache.on('expired', (key, value) => {
console.log(`${key} 已过期`);
});
memory-cache 是最简化的内存缓存,API 极少。
const cache = require('memory-cache');
cache.put('key', 'value', 1000 * 60 * 5);
const value = cache.get('key');
cache.del('key');
cache-manager 是缓存抽象层,可切换不同存储后端。
const cacheManager = require('cache-manager');
const cache = await cacheManager.caching({
store: 'memory',
ttl: 300
});
await cache.set('key', 'value');
const value = await cache.get('key');
cacheable-request 自动缓存 HTTP 请求,遵循 HTTP 缓存标准。
const CacheableRequest = require('cacheable-request');
const http = require('http');
const cacheableRequest = new CacheableRequest(http.request);
cacheableRequest('https://api.example.com/data', {
cacheOptions: { ttl: 1000 * 60 * 5 }
}, (response) => {
// 可能是网络请求或缓存命中
});
axios-cache-adapter 为 axios 添加缓存拦截器。
import axios from 'axios';
import { setupCache } from 'axios-cache-adapter';
const axiosInstance = setupCache(axios.create(), {
maxAge: 5 * 60 * 1000
});
axiosInstance.get('/api/data');
缓存包的性能差异直接影响应用响应时间。
lru-cache 性能最优,无额外依赖,适合高频访问场景。
// lru-cache: 直接内存操作,无序列化开销
const cache = new LRUCache({ max: 10000 });
for (let i = 0; i < 10000; i++) {
cache.set(`key-${i}`, { data: i });
}
// get 操作接近 O(1)
node-cache 性能良好,但会克隆数据避免引用问题。
// node-cache: 自动克隆返回数据
const cache = new NodeCache({ clone: true });
cache.set('key', { mutable: true });
const result = cache.get('key');
// result 是副本,修改不影响缓存
memory-cache 性能不错,但无 LRU 淘汰,内存可能无限增长。
// memory-cache: 无最大容量限制
const cache = require('memory-cache');
// 需要手动管理内存,否则可能泄漏
cache-manager 有抽象层开销,但可配置高性能后端。
// cache-manager: 可切换 Redis 等后端
const cache = await cacheManager.caching({
store: 'redis',
host: 'localhost',
port: 6379
});
// 生产环境可用分布式缓存
cacheable-request 有 HTTP 解析开销,但减少网络请求。
// cacheable-request: 缓存响应体和头
const cacheableRequest = new CacheableRequest(http.request);
// 首次请求走网络,后续命中缓存
axios-cache-adapter 有拦截器开销,但集成简单。
// axios-cache-adapter: 拦截请求响应
const axiosInstance = setupCache(axios.create());
// 每次请求都经过缓存检查
不同包处理缓存过期的方式差异很大。
lru-cache 支持 TTL 和基于容量的 LRU 淘汰。
const cache = new LRUCache({
max: 500,
ttl: 1000 * 60 * 5,
updateAgeOnGet: true // 访问时刷新 TTL
});
cache.set('key', 'value');
// 5 分钟后自动过期,或容量满时淘汰最旧项
node-cache 支持全局和单项 TTL,有事件通知。
const cache = new NodeCache({ stdTTL: 300 });
cache.set('key', 'value', 60); // 单项 60 秒
cache.set('key2', 'value2'); // 使用全局 300 秒
cache.on('expired', (key) => {
console.log(`${key} 过期了`);
});
memory-cache 仅支持单项 TTL,无淘汰机制。
const cache = require('memory-cache');
cache.put('key', 'value', 1000 * 60 * 5);
// 超时后自动删除,但无容量限制
cache-manager 支持 TTL,具体行为取决于存储后端。
const cache = await cacheManager.caching({
store: 'memory',
ttl: 300
});
await cache.set('key', 'value', 60); // 可覆盖全局 TTL
cacheable-request 遵循 HTTP 缓存头,支持 ETag 验证。
cacheableRequest('https://api.example.com/data', {
cacheOptions: {
ttl: 1000 * 60 * 5,
shared: false
}
});
// 尊重服务器的 Cache-Control、ETag 头
axios-cache-adapter 基于请求配置 TTL,可自定义缓存键。
const axiosInstance = setupCache(axios.create(), {
maxAge: 5 * 60 * 1000,
exclude: { query: false } // 查询参数影响缓存键
});
axiosInstance.get('/api/data', {
cache: {
maxAge: 10 * 60 * 1000 // 可覆盖全局配置
}
});
推荐:axios-cache-adapter 或 cacheable-request
// axios-cache-adapter: 已用 axios 的项目
const axiosInstance = setupCache(axios.create(), {
maxAge: 5 * 60 * 1000
});
const response = await axiosInstance.get('/api/users');
// cacheable-request: 需要 HTTP 语义缓存
const cacheableRequest = new CacheableRequest(http.request);
cacheableRequest('https://api.example.com/users', (res) => {
// 自动处理 304 Not Modified
});
推荐:lru-cache
const cache = new LRUCache({
max: 1000,
ttl: 1000 * 60 * 10
});
function expensiveCalculation(input) {
if (cache.has(input)) {
return cache.get(input);
}
const result = doExpensiveWork(input);
cache.set(input, result);
return result;
}
推荐:cache-manager
// 开发用内存,生产用 Redis
const cache = await cacheManager.caching({
store: process.env.NODE_ENV === 'production' ? 'redis' : 'memory',
host: 'localhost',
ttl: 300
});
await cache.set('config', appConfig);
推荐:node-cache
const cache = new NodeCache({ stdTTL: 600 });
cache.set('session:user123', sessionData);
cache.set('config:feature-flags', flags);
// 支持批量操作
cache.mset([
{ key: 'a', val: 1 },
{ key: 'b', val: 2 }
]);
注意:memory-cache 已不推荐用于新项目
// memory-cache: 仅建议维护旧项目时使用
const cache = require('memory-cache');
// 多年未更新,存在潜在安全问题
根据官方仓库和 npm 页面信息:
| 包名 | 维护状态 | 建议 |
|---|---|---|
lru-cache | ✅ 活跃维护 | 新项目首选内存缓存 |
node-cache | ✅ 持续维护 | 适合简单键值缓存 |
cache-manager | ✅ 活跃维护 | 需要抽象层时选择 |
cacheable-request | ✅ 持续维护 | HTTP 缓存场景 |
axios-cache-adapter | ⚠️ 维护频率低 | 评估替代方案 |
memory-cache | ❌ 多年未更新 | 不推荐新项目使用 |
memory-cache 最后更新时间较久,存在潜在安全风险和兼容性问题。新项目应避免使用,可迁移到 node-cache 或 lru-cache。
axios-cache-adapter 虽然功能完整,但维护频率较低。如果项目强依赖 axios 缓存,可考虑社区 fork 版本或迁移到更活跃的 HTTP 缓存方案。
| 特性 | lru-cache | node-cache | memory-cache | cache-manager | cacheable-request | axios-cache-adapter |
|---|---|---|---|---|---|---|
| 存储类型 | 内存 | 内存 | 内存 | 多后端 | 内存 + 文件 | 内存 |
| LRU 淘汰 | ✅ | ❌ | ❌ | 取决于后端 | ❌ | ❌ |
| TTL 支持 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| HTTP 语义 | ❌ | ❌ | ❌ | ❌ | ✅ | ⚠️ 部分 |
| 事件回调 | ⚠️ 有限 | ✅ | ❌ | ✅ | ❌ | ❌ |
| TypeScript | ✅ | ⚠️ 社区类型 | ❌ | ✅ | ✅ | ✅ |
| 维护状态 | ✅ 活跃 | ✅ 活跃 | ❌ 停滞 | ✅ 活跃 | ✅ 活跃 | ⚠️ 低频 |
需要缓存什么?
├── HTTP 请求响应
│ ├── 已用 axios? → `axios-cache-adapter`
│ └── 需要 HTTP 标准缓存? → `cacheable-request`
├── 计算结果/数据对象
│ ├── 需要最高性能? → `lru-cache`
│ ├── 需要事件通知? → `node-cache`
│ └── 需要切换存储后端? → `cache-manager`
└── 维护旧项目
└── 已用 memory-cache? → 计划迁移到 node-cache
新项目优先选择:
lru-cache(性能优先)或 node-cache(功能优先)cacheable-request(标准兼容)cache-manager避免使用:
memory-cache:多年未更新,存在风险axios-cache-adapter:评估更活跃的替代方案关键考量:缓存方案的选择应基于具体场景,而非盲目追求功能最全。简单的内存缓存往往足够,过度设计反而增加维护成本。
选择 lru-cache 如果你需要高性能的纯内存缓存,且能接受手动管理缓存键和过期逻辑。它是这些包中性能最好的,没有额外依赖,API 简洁。适合缓存计算结果、解析数据等高频访问场景。v7+ 版本使用 TypeScript 重写,类型支持更好。
选择 cacheable-request 如果你需要遵循 HTTP 缓存标准(如 Cache-Control、ETag)来自动缓存 HTTP 请求。它与原生 http/https 模块或 got 配合使用,无需修改现有请求代码。适合需要严格遵循 HTTP 缓存语义的代理服务器、爬虫或 API 网关场景。
选择 node-cache 如果你需要简单易用的内存缓存,支持过期时间和事件回调。它比 memory-cache 维护更活跃,API 友好,支持批量操作和克隆数据。适合中小型 Node.js 服务的内存缓存需求,如会话存储、配置缓存等场景。
选择 cache-manager 如果你需要统一的缓存接口来切换不同存储后端(内存、Redis、文件等)。它提供抽象层,便于在开发和生产环境使用不同缓存策略。适合需要灵活部署、可能从内存缓存迁移到分布式缓存的中大型项目。支持多缓存实例和缓存层级。
选择 memory-cache 如果你需要极简的键值缓存且项目较老。但注意该包已多年未更新,不推荐用于新项目。它的 API 非常简单,支持基本的 set/get/del 操作和过期时间。仅建议在维护旧项目时继续使用。
选择 axios-cache-adapter 如果你的项目已经使用 axios 作为 HTTP 客户端,并且希望以最小改动添加请求缓存功能。它直接集成到 axios 拦截器中,配置简单,支持基于请求参数的缓存键生成。适合前端应用或 Node.js 中需要缓存 API 响应的场景。但注意该包维护频率较低,新项目可考虑更活跃的替代方案。
A cache object that deletes the least-recently-used items.
Specify a max number of the most recently used items that you want to keep, and this cache will keep that many of the most recently accessed items.
This is not primarily a TTL cache, and does not make strong TTL
guarantees. There is no preemptive pruning of expired items by
default, but you may set a TTL on the cache or on a single
set. If you do so, it will treat expired items as missing, and
delete them when fetched. If you are more interested in TTL
caching than LRU caching, check out
@isaacs/ttlcache.
As of version 7, this is one of the most performant LRU implementations available in JavaScript, and supports a wide diversity of use cases. However, note that using some of the features will necessarily impact performance, by causing the cache to have to do more work. See the "Performance" section below.
npm install lru-cache --save
// hybrid module, either works
import { LRUCache } from 'lru-cache'
// or:
const { LRUCache } = require('lru-cache')
// or in minified form for web browsers:
import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs'
// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent
// unsafe unbounded storage.
//
// In most cases, it's best to specify a max for performance, so all
// the required memory allocation is done up-front.
//
// All the other options are optional, see the sections below for
// documentation on what each one does. Most of them can be
// overridden for specific items in get()/set()
const options = {
max: 500,
// for use with tracking overall storage size
maxSize: 5000,
sizeCalculation: (value, key) => {
return 1
},
// for use when you need to clean up something when objects
// are evicted from the cache
dispose: (value, key, reason) => {
freeFromMemoryOrWhatever(value)
},
// for use when you need to know that an item is being inserted
// note that this does NOT allow you to prevent the insertion,
// it just allows you to know about it.
onInsert: (value, key, reason) => {
logInsertionOrWhatever(key, value)
},
// how long to live in ms
ttl: 1000 * 60 * 5,
// return stale items before removing from cache?
allowStale: false,
updateAgeOnGet: false,
updateAgeOnHas: false,
// async method to use for cache.fetch(), for
// stale-while-revalidate type of behavior
fetchMethod: async (key, staleValue, { options, signal, context }) => {},
}
const cache = new LRUCache(options)
cache.set('key', 'value')
cache.get('key') // "value"
// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)
cache.clear() // empty the cache
If you put more stuff in the cache, then less recently used items will fall out. That's what an LRU cache is.
For full description of the API and all options, please see the LRUCache typedocs
This implementation aims to be as flexible as possible, within the limits of safe memory consumption and optimal performance.
At initial object creation, storage is allocated for max items.
If max is set to zero, then some performance is lost, and item
count is unbounded. Either maxSize or ttl must be set if
max is not specified.
If maxSize is set, then this creates a safe limit on the
maximum storage consumed, but without the performance benefits of
pre-allocation. When maxSize is set, every item must provide
a size, either via the sizeCalculation method provided to the
constructor, or via a size or sizeCalculation option provided
to cache.set(). The size of every item must be a positive
integer.
If neither max nor maxSize are set, then ttl tracking must
be enabled. Note that, even when tracking item ttl, items are
not preemptively deleted when they become stale, unless
ttlAutopurge is enabled. Instead, they are only purged the
next time the key is requested. Thus, if ttlAutopurge, max,
and maxSize are all not set, then the cache will potentially
grow unbounded.
In this case, a warning is printed to standard error. Future
versions may require the use of ttlAutopurge if max and
maxSize are not specified.
If you truly wish to use a cache that is bound only by TTL
expiration, consider using a Map object, and calling
setTimeout to delete entries when they expire. It will perform
much better than an LRU cache.
Here is an implementation you may use, under the same license as this package:
// a storage-unbounded ttl cache that is not an lru-cache
const cache = {
data: new Map(),
timers: new Map(),
set: (k, v, ttl) => {
if (cache.timers.has(k)) {
clearTimeout(cache.timers.get(k))
}
cache.timers.set(
k,
setTimeout(() => cache.delete(k), ttl),
)
cache.data.set(k, v)
},
get: k => cache.data.get(k),
has: k => cache.data.has(k),
delete: k => {
if (cache.timers.has(k)) {
clearTimeout(cache.timers.get(k))
}
cache.timers.delete(k)
return cache.data.delete(k)
},
clear: () => {
cache.data.clear()
for (const v of cache.timers.values()) {
clearTimeout(v)
}
cache.timers.clear()
},
}
If that isn't to your liking, check out @isaacs/ttlcache.
This cache never stores undefined values, as undefined is used
internally in a few places to indicate that a key is not in the
cache.
You may call cache.set(key, undefined), but this is just
an alias for cache.delete(key). Note that this has the effect
that cache.has(key) will return false after setting it to
undefined.
cache.set(myKey, undefined)
cache.has(myKey) // false!
If you need to track undefined values, and still note that the
key is in the cache, an easy workaround is to use a sigil object
of your own.
import { LRUCache } from 'lru-cache'
const undefinedValue = Symbol('undefined')
const cache = new LRUCache(...)
const mySet = (key, value) =>
cache.set(key, value === undefined ? undefinedValue : value)
const myGet = (key, value) => {
const v = cache.get(key)
return v === undefinedValue ? undefined : v
}
Most methods can accept a status option, which is an
LRUCache.Status
object that will be decorated along the operation with
indications about what was done and why.
Additionally, this library is instrumented using the
node:diagnostics_channel
module on Node and other platforms that support it. In order to
get diagnostics metrics, listen on the
channel('lru-cache:metrics'). To get Tracing Channel traces,
subscribe to the tracingChannel('lru-cache'). The
LRUCache.Status
objects will be provided as the message context to those channel
listeners.
For example, you could do the following to get comprehensive information about every LRUCache instance in your application:
import { tracingChannel, subscribe } from 'node:diagnostics_channel'
subscribe('lru-cache:metrics', (message, name) => {
// name will always be 'lru-cache:metrics'
// message will be the LRUCache.Status object for whatever
// synchronous operation was performed.
console.error('LRUCache Metrics', message)
})
tracingChannel('lru-cache').subscribe({
start: status => {
// a traced operation is starting
},
asyncStart: status => {
// an async traced operation is starting
},
asyncEnd: status => {
// an async traced operation is ending
}
error: status => {
// a traced operation failed
},
end: status => {
// a traced operation is complete
},
})
The async cache.fetch() and cache.forceFetch methods are
covered by tracingChannels. All the other operations are
covered by the lru-cache:metrics channel, because they are
strictly synchronous, and thus don't have an asynchronous
lifecycle to track.
Note that using status objects or using
node:diagnostics_channel listeners will impose a modest
performance penalty. Creating data objects is not ever free; do
not believe anyone who tells you otherwise. But it is as small as
possible.
Not all platforms support the node:diagnostics_channel module.
Currently, this is only available in Node, Bun, and Deno, and
some edge computing platforms that provide a Node compatibility
layer.
To work around this, if you are loading in a non-Node
environment, the package.json exports will direct your module
loader to pull in a version that starts out with a dummy
implementation, then does a conditional dynamic import of the
node:diagnostics_channel module, and then swaps out those
dummy objects with the real thing if it succeeds. This means that
cache metrics and tracing channels started in the first load-time
tick of your application will not be covered, except in
environments that load using the require import
condition, or both the node and esm import conditions
together.
Top-level await could be used to remove this caveat, but that feature is dead on arrival, unfortunately. See #397 and #398 for more details.
As of April 2026, version 11 of this library is one of the most performant LRU cache implementations in JavaScript.
Benchmarks can be extremely difficult to get right. In particular, the performance of set/get/delete operations on objects will vary wildly depending on the type of key used. V8 is highly optimized for objects with keys that are short strings, especially integer numeric strings. Thus any benchmark which tests solely using numbers as keys will tend to find that an object-based approach performs the best.
Note that coercing anything to strings to use as object keys is unsafe, unless you can be 100% certain that no other type of value will be used. For example:
const myCache = {}
const set = (k, v) => (myCache[k] = v)
const get = k => myCache[k]
set({}, 'please hang onto this for me')
set('[object Object]', 'oopsie')
Also beware of "Just So" stories regarding performance. Garbage collection of large (especially: deep) object graphs can be incredibly costly, with several "tipping points" where it increases exponentially. As a result, putting that off until later can make it much worse, and less predictable. If a library performs well, but only in a scenario where the object graph is kept shallow, then that won't help you if you are using large objects as keys.
In general, when attempting to use a library to improve performance (such as a cache like this one), it's best to choose an option that will perform well in the sorts of scenarios where you'll actually use it.
This library is optimized for repeated gets and minimizing eviction time, since that is the expected need of a LRU. Set operations are somewhat slower on average than a few other options, in part because of that optimization. It is assumed that you'll be caching some costly operation, ideally as rarely as possible, so optimizing set over get would be unwise.
If performance matters to you:
If it's at all possible to use small integer values as keys, and you can guarantee that no other types of values will be used as keys, then do that, and use a cache such as lru-fast, or mnemonist's LRUCache which uses an Object as its data store.
Failing that, if you can use short non-numeric strings (ie, less than 256 characters) as your keys, and you do not need any of the other features of this library, use mnemonist's LRUCache.
If the types of your keys will be anything else, especially long strings, strings that look like floats, objects, or some mix of types, or if you aren't sure, then this library will work well for you.
If you do not need the features that this library provides (like asynchronous fetching, a variety of TTL staleness options, and so on), then mnemonist's LRUMap is also a very good option, and just slightly faster than this module (since it does considerably less).
Do not use a dispose function, size tracking, or especially
ttl behavior or observability features, unless absolutely
needed. These features are convenient, and necessary in some
use cases, and every attempt has been made to make the
performance impact minimal, but it isn't nothing.
When writing tests that involve TTL-related functionality, note
that this module creates an internal reference to the global
performance or Date objects at import time. If you import it
statically at the top level, those references cannot be mocked or
overridden in your test environment.
To avoid this, dynamically import the package within your tests so that the references are captured after your mocks are applied. For example:
// ❌ Not recommended
import { LRUCache } from 'lru-cache'
// mocking timers, e.g. jest.useFakeTimers()
// ✅ Recommended for TTL tests
// mocking timers, e.g. jest.useFakeTimers()
const { LRUCache } = await import('lru-cache')
This ensures that your mocked timers or time sources are respected when testing TTL behavior.
Additionally, you can pass in a perf option when creating your
LRUCache instance. This option accepts any object with a now
method that returns a number.
For example, this would be a very bare-bones time-mocking system you could use in your tests, without any particular test framework:
import { LRUCache } from 'lru-cache'
let myClockTime = 0
const cache = new LRUCache<string>({
max: 10,
ttl: 1000,
perf: {
now: () => myClockTime,
},
})
// run tests, updating myClockTime as needed
This library changed to a different algorithm and internal data structure in version 7, yielding significantly better performance, albeit with some subtle changes as a result.
If you were relying on the internals of LRUCache in version 6 or before, it probably will not work in version 7 and above.
fetchContext option was renamed to context, and may no
longer be set on the cache instance itself.null or undefined.'lru-cache/min', for both CJS
and MJS builds.cache.fetch() return type is now Promise<V | undefined>
instead of Promise<V | void>. This is an irrelevant change
practically speaking, but can require changes for TypeScript
users.For more info, see the change log.