小布工坊.
← Back to the library

Resource details · 实用工具

带有效期与容量上限的小缓存

保存少量临时字符串,过期后返回空值,容量达到上限时移除最早写入者。

Resource text, examples and licences retain their original language. Code is displayed only; this page does not execute it or call AI.

Resource details

适合学习Map、TTL和容量控制。只在本次进程的内存中工作,调用get、set、size时清理;不是LRU,不建立定时器,也不是数据库。

Before you start

Platforms
Windows · macOS · Linux
Content updated
  • 准备Node.js 24和文本编辑器;本站仅在Node.js v24.19.0本地核对。
  • 了解Map、毫秒时间和缓存命中的概念。
node ttl-cache.mjs

先在文件所在目录打开终端。无需 npm install;本例不联网、不读写用户文件,不能直接代替生产平台接入。

Common pitfalls

  • 按指定.mjs文件名保存,避免变成.mjs.txt;不需要npm install。
  • 方法调用才清理过期数据;这是写入顺序淘汰,不是LRU。
Official setup guide ↗

Complete resource

// SPDX-License-Identifier: MIT
// 原创教学示例:限量字符串缓存;到期检查由调用触发,不建立定时器。
export function createTTLCache(options = {}) {
  if (!options || typeof options !== "object" || Array.isArray(options)) throw new TypeError("选项需为对象");
  const { capacity = 20, ttlMs = 1000 } = options;
  if (!Number.isInteger(capacity) || capacity < 1 || capacity > 200) throw new RangeError("容量需为1至200");
  if (!Number.isSafeInteger(ttlMs) || ttlMs < 1 || ttlMs > 86400000) throw new RangeError("有效期需为1毫秒至1天");
  const entries = new Map();
  let lastTime = 0;
  function checkKey(key) {
    if (typeof key !== "string" || !key.length || key.length > 80) throw new TypeError("键需为1至80字符");
  }
  function expire(nowMs) {
    if (!Number.isSafeInteger(nowMs) || nowMs < 0 || nowMs > Number.MAX_SAFE_INTEGER - ttlMs) throw new RangeError("时间无效");
    const now = Math.max(nowMs, lastTime); // 时钟回拨不会复活已经过期的条目。
    lastTime = now;
    for (const [key, entry] of entries) if (entry.until <= now) entries.delete(key);
    return now;
  }
  return {
    set(key, value, nowMs = Date.now()) {
      checkKey(key);
      if (typeof value !== "string" || value.length > 2000) throw new TypeError("值需为最多2000字符的字符串");
      const now = expire(nowMs);
      entries.delete(key);
      if (entries.size >= capacity) entries.delete(entries.keys().next().value);
      entries.set(key, { value, until: now + ttlMs }); // 移除最早写入者,不是LRU。
    },
    get(key, nowMs = Date.now()) {
      checkKey(key); expire(nowMs);
      return entries.get(key)?.value ?? null;
    },
    size(nowMs = Date.now()) { expire(nowMs); return entries.size; },
  };
}

const cache = createTTLCache({ capacity: 2, ttlMs: 100 });
cache.set("a", "早餐", 0); cache.set("b", "午饭", 10);
const hit = cache.get("a", 50);
cache.set("c", "晚饭", 60);
const evicted = cache.get("a", 60), remaining = cache.size(110);
console.log(JSON.stringify({ hit, evicted, remaining, expired: cache.get("c", 160) }));

How to use it

用明确的演示毫秒值观察命中、容量淘汰和到期;不需要修改系统时钟。

  1. 保存完整教学代码

    点击下载代码,或复制正文保存为ttl-cache.mjs。保留许可说明;不要混入Markdown三反引号,确认后缀不是.mjs.txt。

  2. 在文件夹中运行

    准备Node.js 24,在保存文件的目录打开终端,执行下方node命令;不需要账号、密钥或第三方依赖。

  3. 核对结果后再修改

    核对hit为早餐、evicted为null、remaining为1、expired为null。把容量改为1,再观察较早写入的键被移除。

Save as
ttl-cache.mjs
Environment
Node.js 24;本站运行核验为v24.19.0。保存为.mjs,无需npm install。
Dependencies and costs
代码不联网、不调用模型、不读写用户文件;无接口费用。设备和电力成本由使用者承担,接入实际应用后的成本另行核对。

Command

node ttl-cache.mjs

Expected output

{"hit":"早餐","evicted":null,"remaining":1,"expired":null}

Local verification

2026-10-22 · Node.js v24.19.0

已在本站本机运行此页原样附带的教学代码,并核对演示输出及本批注明的边界测试;不代表生产验证、全平台实测或安全审计。

Suitable uses

  • 学习小型临时缓存
  • 理解容量与TTL是两种独立限制

Before using it

  • 仅存字符串,每值最多2000字符,容量最多200;不支持任意对象。
  • 检查由方法调用触发,进程空闲时不会自动清理;读操作也不刷新有效期。
  • 用Map存键,键名不会写入对象原型;输入时间回拨会被钳在最近时刻。缓存没有持久化。

Authors and sources

Attribution
包子海梦 · AI辅助开发
Authors and sources
提示集贡献者

Notices and modifications

新编写的通用教学示例,发布前仍需核对来源与运行效果。

Complete licence

MIT

MIT License

Copyright (c) 2026 提示集贡献者

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Verification scope

教学代码已运行

已运行完整带许可的教学文件并核对输出;不代表生产部署、平台接入或全部边界情况都已验证。

2026-10-23 Node.js v24.19.0