fix(缓存): 修复小文件缓存大小不一致时重新获取的逻辑

当缓存文件大小小于2KB且与请求头中的content-length不一致时,重新获取文件内容,确保缓存数据的准确性
This commit is contained in:
XiaoMo 2025-05-24 23:29:34 +08:00
parent f7dbca480b
commit be808e0174
2 changed files with 8 additions and 2 deletions

File diff suppressed because one or more lines are too long

View File

@ -175,9 +175,15 @@ const server = http.createServer(async (req, res) => {
tempCacheContentFile = pathModule.join(cacheDir, `${data.uniqid}_${crypto.randomBytes(16).toString('hex')}.temp`); tempCacheContentFile = pathModule.join(cacheDir, `${data.uniqid}_${crypto.randomBytes(16).toString('hex')}.temp`);
// 重新写入 meta 缓存 // 重新写入 meta 缓存
fs.writeFileSync(cacheMetaFile, JSON.stringify(data)); fs.writeFileSync(cacheMetaFile, JSON.stringify(data));
// 如果内容缓存存在, 则直接调用 // 如果内容缓存存在, 则直接调用
if (fs.existsSync(cacheContentFile)) { if (fs.existsSync(cacheContentFile)) {
// 读取大小是否一致
const contentLength = fs.statSync(cacheContentFile).size;
// 如果文件小于 2KB, 且与缓存文件大小不一致时,重新获取
if (contentLength < 2048 && data.headers['content-length'] !== contentLength) {
fetchAndServe(data, tempCacheContentFile, cacheContentFile, cacheMetaFile, res);
return;
}
serveFromCache(data, cacheContentFile, cacheMetaFile, res); serveFromCache(data, cacheContentFile, cacheMetaFile, res);
} else { } else {
fetchAndServe(data, tempCacheContentFile, cacheContentFile, cacheMetaFile, res); fetchAndServe(data, tempCacheContentFile, cacheContentFile, cacheMetaFile, res);