http-cache-semantics

中文文档
4.3.0发布于 2026/10/04BSD-2-ClauseTypeScriptCommonJS零依赖近 30 天下载 2.1亿

解析缓存控制和其他信头 。 帮助建立正确的 HTTP 缓存和代理

中文使用文档
文档目录15 节
  1. 基本用途
  2. 构造选项
  3. storable()
  4. satisfiesWithoutRevalidation(newRequest)
  5. responseHeaders()
  6. timeToLive()
  7. toObject() 编号 : fromObject(json)
  8. 完成使用
  9. evaluateRequest(newRequest)
  10. 示例
  11. 刷新 stale 缓存( 重新验证)
  12. 用于
  13. 已执行
  14. 未执行
  15. 信任服务器 Date

我可以缓存这个吗?

此库说明何时可以从缓存中重用回复, 同时考虑到 HTTP RFC 7234/9111 导弹 用于用户代理和共享缓存的规则. 它还执行 stale-if-error 财务报告和审定财务报表 stale-while-revalidate 从 RFC 5861 (韩语)。 。 。 . 它知道很多棘手的细节 比如.. Vary 头,代理重新验证,和认证的回复.

基本用途

CachePolicy 是一个元数据对象,意在存储在缓存中,它将跟踪响应的缓存性.

HTTP 响应的可缓存性取决于它是如何请求的,所以两者都是 request 财务报告和审定财务报表 response 需要制定该政策.

const policy = new CachePolicy(request, response, options);

if (!policy.storable()) {
    // throw the response away, it's not usable at all
    return;
}

// Cache the data AND the policy object in your cache
// (this is pseudocode, roll your own cache (lru-cache package works))
letsPretendThisIsSomeCache.set(
    request.url,
    { policy, body: response.body }, // you only need to store the response body. CachePolicy holds the headers.
    policy.timeToLive()
);
// And later, when you receive a new request:
const { policy, body } = letsPretendThisIsSomeCache.get(newRequest.url);

// It's not enough that it exists in the cache, it has to match the new request, too:
if (policy && policy.satisfiesWithoutRevalidation(newRequest)) {
    // OK, the previous response can be used to respond to the `newRequest`.
    // Response headers have to be updated, e.g. to add Age and remove uncacheable headers.
    return {
        headers: policy.responseHeaders(),
        body,
    }
}

// Cache miss. See revalidationHeaders() and revalidatedPolicy() for advanced usage.

这也许令人惊讶,但单靠HTTP反应是不够的 新鲜 满足一个请求。 它可能需要匹配请求头 Vary。即使匹配的新响应,如果新请求限制缓存性等,也可能仍然无法使用.

关键方法是 satisfiesWithoutRevalidation(newRequest),检查是否 newRequest 符合原始请求,以及是否符合所有缓存条件.

构造选项

请求和答复必须有 headers 属性,小写后所有标题. url, (中文(简体) ), status 财务报告和审定财务报表 method 是可选的( 默认是任意 URL, 状态) 200,以及 GET 页:1.

const request = {
    url: '/',
    method: 'GET',
    headers: {
        accept: '*/*',
    },
};

const response = {
    status: 200,
    headers: {
        'cache-control': 'public, max-age=7234',
    },
};

const options = {
    shared: true,
    cacheHeuristic: 0.1,
    immutableMinTimeToLive: 24 * 3600 * 1000, // 24h
    ignoreCargoCult: false,
};

若为 options.shared 实值 true (默认),然后从共享缓存(即:. private 不可缓存和 s-maxage (见E/CN.4/Sub.2/2003/L.10和Add.1和2) 若为 options.shared 实值 false,然后从单个用户缓存(即:. private 可缓存和 s-maxage 页:1. shared: true 建议HTTP客户端.

options.cacheHeuristic 是作为后退缓存持续时间的响应年龄的一小部分。 默认为0.1 (10%),例如如果一个文件有100天没有被修改,它会被缓存100*0.1=10天.

options.immutableMinTimeToLive 是数以毫秒作为缓存回复的默认时间 Cache-Control: immutable。注意: 每个RFC 这些会变得僵化,所以 max-age 仍然覆盖默认值.

若为 options.ignoreCargoCult 如果非标准, 常见的防缓存指令将被完全忽略 pre-check 财务报告和审定财务报表 post-check 有指令存在。 这两种无用指令最常见于坏 Stack Overflow 答案和PHP的"会话限制器"默认.

storable()

回返 true 如果响应可以存储在缓存中。 如果是这样 false 您必须不存储请求或回复.

satisfiesWithoutRevalidation(newRequest)

使用这种方法来检查缓存响应在新请求的上下文中是否仍然新鲜.

如果它回来了 true,然后给定 request 匹配此缓存策略已创建的原始响应, 并且该响应无需联系服务器即可被再使用 。 注意,没有更新,旧的响应无法返回 responseHeaders()。 。 。 .

如果它回来了 false,则该响应可能根本不匹配(例如它用于不同的URL或方法),或可能需要先被刷新(参见 revalidationHeaders()) (中文(简体) ).

responseHeaders()

返回更新,过滤的一组响应头,以返回接受缓存响应的客户端. 此功能是必需的, 因为代理 MUST 总是去除 hop- by- hop headers( 例如 TE 财务报告和审定财务报表 Connection) 和更新回复 Age 以避免缓存时间翻倍.

cachedResponse.headers = cachePolicy.responseHeaders();

timeToLive()

建议时间在 毫秒 用于此缓存条目可能有用的时间。 这不是新鲜的,所以总是检查 satisfiesWithoutRevalidation()。这一次可能比答复的时间更长 max-age 允许 stale-if-error 财务报告和审定财务报表 stale-while-revalidate。 。 。 .

之后(何时) timeToLive() <= 0)该响应在某些情况下可能仍然可用,例如,如果客户端可以明确允许呆滞响应.

toObject()编号 :fromObject(json)

你会想储存 CachePolicy 对象与缓存的响应. obj = policy.toObject() 给出一个简单的 JSON 序列大小对象. policy = CachePolicy.fromObject(obj) 从中创造一个实例.

完成使用

evaluateRequest(newRequest)

返回告诉下一步要做什么的对象——可选 revalidation选择 response 从缓存。 其中任何一个都会存在 两者可能同时出席.

{
    // If defined, you must send a request to the server.
    revalidation: {
        headers: {}, // HTTP headers to use when sending the revalidation response
        // If true, you MUST wait for a response from the server before using the cache
        // If false, this is stale-while-revalidate. The cache is stale, but you can use it while you update it asynchronously.
        synchronous: bool,
    },
    // If defined, you can use this cached response.
    response: {
        headers: {}, // Updated cached HTTP headers you must use when responding to the client
    },
}

示例

let cached = cacheStorage.get(incomingRequest.url);

// Cache miss - make a request to the origin and cache it
if (!cached) {
    const newResponse = await makeRequest(incomingRequest);
    const policy = new CachePolicy(incomingRequest, newResponse);

    cacheStorage.set(
        incomingRequest.url,
        { policy, body: newResponse.body },
        policy.timeToLive()
    );

    return {
        // use responseHeaders() to remove hop-by-hop headers that should not be passed through proxies
        headers: policy.responseHeaders(),
        body: newResponse.body,
    }
}

// There's something cached, see if it's a hit
let { revalidation, response } = cached.policy.evaluateRequest(incomingRequest);

// Revalidation always goes first
if (revalidation) {
    // It's very important to update the request headers to make a correct revalidation request
    incomingRequest.headers = revalidation.headers; // Same as cached.policy.revalidationHeaders()

    // The cache may be updated immediately or in the background,
    // so use a Promise to optionally defer the update
    const updatedResponsePromise = makeRequest(incomingRequest).then(() => {
        // Refresh the old response with the new information, if applicable
        const { policy, modified } = cached.policy.revalidatedPolicy(incomingRequest, newResponse);

        const body = modified ? newResponse.body : cached.body;

        // Update the cache with the newer response
        if (policy.storable()) {
            cacheStorage.set(
                incomingRequest.url,
                { policy, body },
                policy.timeToLive()
            );
        }

        return {
            headers: policy.responseHeaders(), // these are from the new revalidated policy
            body,
        }
    });

    if (revalidation.synchronous) {
        // If synchronous, then you MUST get a reply from the server first
        return await updatedResponsePromise;
    }

    // If not synchronous, it can fall thru to returning the cached response,
    // while the request to the server is happening in the background.
}

return {
    headers: response.headers, // Same as cached.policy.responseHeaders()
    body: cached.body,
}

刷新 stale 缓存( 重新验证)

当缓存响应已过期时,可以通过向源服务器提出请求再次被刷新. 服务器可能以状态304(没有被修改)响应,而不再次发送响应正文,节省带宽.

以下方法有助于有效和正确地进行更新.

revalidationHeaders(newRequest)

返回更新,过滤的请求信头集,以发送到源服务器,以检查缓存响应是否可以被再利用. 这些信头允许源服务器返回状态 304 表示响应仍然新鲜. 所有与卡通无关的车头都是按原样通过.

从源服务器上更新缓存时使用此方法 。 也可查阅 evaluateRequest(newRequest).revalidation.headers。 。 。 .

updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest);

revalidatedPolicy(revalidationRequest, revalidationResponse)

使用这种方法在从源服务器收到新响应后更新缓存. 它返回一个带有两个键的对象:

  • policy -一个新的 CachePolicy 并更新 HTTP 头来自 revalidationResponse。您总是可以替换旧的缓存 CachePolicy 与新的一个.
  • modified ——布尔表示响应正体是否改变,您应当使用服务器发送的新响应正体.
    • 若为 true,您应当使用新的响应正文,并且可以将旧的缓存响应替换为更新的响应.
    • 若为 false,那么你应该重新使用旧的缓存反应机体。 要么收到有效的304没有修改的答复,要么发生错误 stale-if-error 允许返回缓存.

哟,FRESH

satisfiesWithoutRevalidation

用于

已执行

  • Cache-Control 反应头和所有的怪异.
  • Expires 检查坏钟.
  • Pragma 响应头.
  • Age 响应头.
  • Vary 响应头.
  • 状态和方法的默认缓存性 .
  • 要求提供陈旧的数据.
  • 逐一过滤 hop-by-hop headers.
  • 基本重新验证请求
  • stale-if-error
  • stale-while-revalidate

未执行

  • 合并范围请求, If-Range (但正确支持它们为不可取)
  • 更改多重表述

信任服务器 Date

根据 RFC ,缓存应当考虑服务器提供之间的时间 Date 以及收到答复的时间。 RFC授权的行为造成了两个问题:

  • 设置错误的时区服务器可能会为缓存年龄增加数小时(或者更多,如果时钟完全错误).
  • 即使是合理正确的时钟 也可能关闭几秒钟,打破 max-age=1 trick (用于高流量服务器上的反向代理).

此库的前几个版本如果"太不准确",可以忽略服务器日期. 支持 max-age=1 {\fn黑体\fs22\bord1\shad0\3aHBE\4aH00\fscx67\fscy66\2cHFFFFFF\3cH808080}图书室也得忽略如此准确的日期 没有任何意义可以选择只信任一点不准确的日期,因此这个库不会信任任何服务器日期. max-age 将从收到答复时而不是从发出答复时开始解释。 这只会影响 RFC 1149网络。 。 。 .

版本与发布记录

http-cache-semantics 共发布 30 个版本,首次发布于 2016/05/31;过去 12 个月发布了 1 个版本。

版本发布日期距今
4.3.0latest2026/10/041 个月前
4.2.02025/05/091.5 年前
4.2.0-beta.2next2025/03/191.6 年前
4.2.0-beta.1beta2025/02/031.8 年前
4.1.12023/01/273 年前
4.1.02020/03/026 年前

关于 http-cache-semantics 的常见问题

http-cache-semantics 是什么?

解析缓存控制和其他信头 。 帮助建立正确的 HTTP 缓存和代理

如何安装 http-cache-semantics?

在项目目录运行 npm install http-cache-semantics,或使用 pnpm add / yarn add / bun add。

http-cache-semantics 支持 TypeScript 吗?

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

http-cache-semantics 支持 ESM 还是 CommonJS?

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

http-cache-semantics 可以商用吗?

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

http-cache-semantics 的下载量有多少?

根据 npm 官方下载统计,http-cache-semantics 在 2026/10/05 – 2026/11/03 这 30 天内被下载 214,079,411 次,日均约 7,135,980 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

http-cache-semantics 还在维护吗?

最新版本 4.3.0 发布于 2026/10/04(1 个月前);至今共发布 30 个版本,其中过去 12 个月发布了 1 个;首次发布于 2016/05/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。