UNPKG

zyf-server

Version:

A modern HTTP static file server with Vue SSR directory listing, built for developers

54 lines 1.6 kB
"use strict"; /** * 缓存管理器 * 处理HTTP缓存策略 */ Object.defineProperty(exports, "__esModule", { value: true }); exports.CacheManager = void 0; class CacheManager { config; constructor(config) { this.config = { maxAge: config?.maxAge ?? 10, etag: config?.etag ?? true, lastModified: config?.lastModified ?? true, }; } /** * 检查资源是否未修改 */ isNotModified(req, stats) { if (!this.config.lastModified) return false; const serverTime = stats.ctime.toUTCString(); const clientTime = req.headers['if-modified-since']; return serverTime === clientTime; } /** * 设置缓存相关头部 */ setHeaders(res, stats) { // 强制缓存 res.setHeader('Cache-Control', `max-age=${this.config.maxAge}`); res.setHeader('Expires', new Date(Date.now() + this.config.maxAge * 1000).toUTCString()); // 对比缓存 - Last-Modified if (this.config.lastModified) { res.setHeader('Last-Modified', stats.ctime.toUTCString()); } // 对比缓存 - ETag if (this.config.etag) { const etag = this.generateETag(stats); res.setHeader('ETag', etag); } } /** * 生成ETag */ generateETag(stats) { const mtime = stats.mtime.getTime().toString(16); const size = stats.size.toString(16); return `"${size}-${mtime}"`; } } exports.CacheManager = CacheManager; //# sourceMappingURL=CacheManager.js.map