lru-cache、memory-cache、node-cache 和 node-persist 都是 Node.js 环境中用于管理缓存的 npm 包,但它们在缓存策略、内存管理、持久化支持和功能特性上有显著差异。lru-cache 基于 LRU(最近最少使用)算法实现高效的内存缓存;memory-cache 提供简单的内存缓存但已废弃;node-cache 支持 TTL(生存时间)过期和可选容量限制;node-persist 则专注于将缓存数据持久化到磁盘,支持进程重启后恢复数据。这些库适用于不同场景,从高性能内存缓存到需要持久化的本地状态存储。
在构建高性能 Node.js 应用时,缓存是提升响应速度、降低数据库压力的关键手段。本文聚焦四个主流内存/持久化缓存方案 —— lru-cache、memory-cache、node-cache 和 node-persist —— 从核心机制、API 设计、适用场景等维度进行深度剖析,帮助开发者做出精准技术选型。
lru-cache 实现了经典的 最近最少使用(LRU)淘汰策略。当缓存达到容量上限时,自动移除最久未被访问的条目。它不依赖时间过期,而是基于访问频率和容量控制,适合高频读写、内存敏感的场景。
// lru-cache: 基于容量的 LRU 策略
import { LRUCache } from 'lru-cache';
const cache = new LRUCache({
max: 100, // 最多缓存 100 个条目
maxSize: 5000, // 总字节大小限制(需提供 sizeCalculation)
sizeCalculation: (value, key) => JSON.stringify(value).length
});
cache.set('user:123', { name: 'Alice' });
console.log(cache.get('user:123')); // { name: 'Alice' }
memory-cache 提供极简的 TTL(生存时间)过期机制,无容量限制。所有数据常驻内存直至过期或进程退出。适合临时、低频、小规模缓存,但存在内存泄漏风险。
// memory-cache: 简单 TTL 过期
import cache from 'memory-cache';
cache.put('session:abc', { userId: 456 }, 60000); // 60秒后过期
console.log(cache.get('session:abc')); // { userId: 456 }
node-cache 结合了 TTL 过期 + 可选容量限制,支持自动清理过期项(通过 checkperiod)。功能比 memory-cache 更全面,适合需要可控内存占用的通用缓存场景。
// node-cache: TTL + 容量控制
import NodeCache from 'node-cache';
const cache = new NodeCache({
stdTTL: 60, // 默认 60 秒过期
checkperiod: 120, // 每 120 秒清理一次过期项
maxKeys: 1000 // 最多 1000 个键
});
cache.set('config:app', { theme: 'dark' });
console.log(cache.get('config:app')); // { theme: 'dark' }
node-persist 是唯一支持 磁盘持久化 的方案。数据写入本地文件系统,即使进程重启也能恢复。适用于需要跨会话保留状态的场景(如本地开发配置、小型应用状态存储)。
// node-persist: 磁盘持久化
import storage from 'node-persist';
await storage.init(); // 初始化存储目录
await storage.setItem('lastLogin', new Date());
const lastLogin = await storage.getItem('lastLogin');
⚠️ 注意:
memory-cache自 2019 年起已停止维护(npm 页面标记为 deprecated),新项目应避免使用。
所有包都支持基础的 set/get/del 操作,但在高级功能上差异显著。
lru-cache 提供丰富的原子操作:
has(key):检查键是否存在peek(key):获取值但不更新 LRU 顺序delete(key) / clear():删除单个或全部keys(), values(), entries():迭代器支持// lru-cache: peek 不影响 LRU 顺序
const cache = new LRUCache({ max: 2 });
cache.set('a', 1);
cache.set('b', 2);
cache.get('a'); // 访问 'a',使其变为最近使用
cache.peek('b'); // 查看 'b' 但不改变顺序
// 此时再 set('c', 3) 会淘汰 'b'(因为 'a' 最近被访问)
node-cache 支持批量操作:
mset([[key, val, ttl], ...]):批量设置mget([key1, key2]):批量获取mdelete([key1, key2]):批量删除// node-cache: 批量操作
const cache = new NodeCache();
cache.mset([
['k1', 'v1', 100],
['k2', 'v2', 200]
]);
console.log(cache.mget(['k1', 'k2'])); // ['v1', 'v2']
node-persist 也支持批量操作,但均为异步:
setItem(key, val) / getItem(key)setItems({ k1: v1, k2: v2 }) / getItems([k1, k2])removeItem(key) / clear()// node-persist: 异步批量操作
await storage.setItems({ foo: 'bar', baz: 'qux' });
const items = await storage.getItems(['foo', 'baz']);
memory-cache 仅提供基础操作:
put(key, val, time)get(key)del(key) / clear()size():返回当前条目数lru-cache 本身 不支持 TTL(除非使用 ttl 选项,但这是 v7+ 的新特性)。传统用法依赖容量淘汰。若需 TTL,需自行封装或升级到新版。
// lru-cache v7+: 支持 TTL
const cache = new LRUCache({
ttl: 1000 * 60, // 60秒 TTL
ttlAutopurge: true // 自动清理过期项
});
node-cache 的 checkperiod 选项启动后台定时器,定期扫描并删除过期键。若设为 0,则只在 get 时惰性清理。
node-persist 通过 expireInterval 控制过期检查频率(默认 60 秒),支持为每个键单独设置过期时间:
// node-persist: 单独设置过期时间
await storage.setItem('temp', 'data', { ttl: 30000 }); // 30秒后过期
memory-cache 在 get 时检查过期,无后台清理线程。
只有 node-persist 提供磁盘持久化。其他三者均为纯内存存储,进程退出即丢失数据。
node-persist 使用 fs.writeFileSync 写入 JSON 文件,默认存储在 ./.node-persist/storage。// node-persist: 自定义存储路径
await storage.init({
dir: './my-cache',
stringify: JSON.stringify,
parse: JSON.parse
});
lru-cache 和 node-cache 提供事件监听:
// lru-cache: 监听淘汰事件
cache.on('evict', (info) => {
console.log(`淘汰键: ${info.key}, 值: ${info.value}`);
});
// node-cache: 监听过期/删除事件
cache.on('del', (key, val) => {
console.log(`删除: ${key}`);
});
cache.on('expired', (key, val) => {
console.log(`过期: ${key}`);
});
node-persist 无事件系统。memory-cache 也无事件支持。
| 场景 | 推荐方案 | 理由 |
|---|---|---|
| 高频 API 响应缓存 | lru-cache | LRU 策略高效利用有限内存,避免 OOM |
| 临时会话/令牌存储 | node-cache | TTL + 容量控制,平衡内存与功能 |
| 跨进程重启的状态保留 | node-persist | 唯一支持磁盘持久化 |
| 简单原型/脚本 | 避免 memory-cache | 已废弃,有内存泄漏风险 |
lru-cache:如果你需要高性能、内存可控的缓存(尤其是 v7+ 支持 TTL 后),它是工业级首选。node-cache:当你需要简单 TTL、批量操作和事件监听,且能接受后台清理开销。node-persist:仅限单进程、小数据量、需持久化的场景;大数据量应选 Redis 等专业方案。memory-cache:官方已弃用,无维护保障。记住:缓存不是银弹。评估你的数据规模、访问模式、持久化需求和内存预算,才能选出最合适的工具。
选择 lru-cache 如果你需要一个高性能、内存可控的缓存方案,尤其适用于高频读写场景。它基于 LRU 淘汰策略,在达到容量上限时自动移除最久未使用的条目,能有效防止内存溢出。新版(v7+)还支持 TTL 过期和自动清理,适合替代传统 TTL 缓存。注意它默认不持久化,进程退出后数据会丢失。
不要在新项目中使用 memory-cache。该包自 2019 年起已被官方标记为废弃(deprecated),不再维护。它仅提供简单的 TTL 过期机制,没有容量限制,长期运行可能导致内存泄漏。如果已有项目在使用,应尽快迁移到 node-cache 或 lru-cache。
选择 node-cache 如果你需要一个功能均衡的内存缓存方案,支持 TTL 过期、可选容量限制、批量操作和事件监听。它通过后台定时器自动清理过期项,适合通用缓存场景(如会话存储、API 响应缓存)。但要注意其内存占用仍可能增长,需合理设置 maxKeys 和 stdTTL。
选择 node-persist 如果你必须将缓存数据持久化到磁盘,以便在进程重启后恢复状态。它适用于单进程、小数据量的场景(如本地开发配置、小型应用状态存储)。但要注意它不支持多进程并发写入,且性能远低于纯内存方案。对于生产环境的大规模数据,应考虑 Redis 等专业持久化缓存系统。
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.