You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js如何实现文件缓存优化?memoizee包是否适用?

内存缓存优化Node.js静态文件接口

当然可以通过内存缓存来提升这个接口的性能——把文件内容提前读入内存,后续请求直接返回缓存内容,避免重复的磁盘IO操作。下面提供两种实现方式:

手动实现内存缓存

不需要额外依赖包,自己维护缓存状态,适合简单场景:

const fs = require('fs').promises;
const path = require('path');

// 缓存对象,存储文件内容和最后修改时间
let userPageCache = {
  content: null,
  lastModified: null
};

// 封装读取文件的逻辑,带缓存判断
async function getCachedUserPage() {
  const filePath = path.join(distFolder, 'user', 'index.html');
  const fileStats = await fs.stat(filePath);

  // 如果未缓存,或文件已修改,则重新读取
  if (!userPageCache.content || fileStats.mtime > userPageCache.lastModified) {
    userPageCache.content = await fs.readFile(filePath, 'utf8');
    userPageCache.lastModified = fileStats.mtime;
  }

  return userPageCache.content;
}

// 修改接口逻辑,使用缓存
server.get('/user', async (req, res) => {
  try {
    const htmlContent = await getCachedUserPage();
    res.setHeader('Content-Type', 'text/html');
    res.send(htmlContent);
  } catch (error) {
    res.status(500).send('加载用户页面失败');
  }
});

使用memoizee实现缓存

memoizee是专门的缓存工具包,支持Promise、缓存过期、自定义缓存键等特性,可以快速实现缓存逻辑:

  1. 先安装依赖:
npm install memoizee
  1. 修改接口代码:
const fs = require('fs').promises;
const path = require('path');
const memoize = require('memoizee');

// 封装原始的文件读取函数
async function readUserPage() {
  const filePath = path.join(distFolder, 'user', 'index.html');
  return fs.readFile(filePath, 'utf8');
}

// 用memoizee包装,配置缓存规则
const memoizedReadUserPage = memoize(readUserPage, {
  promise: true, // 处理异步Promise函数
  maxAge: 3600000, // 缓存1小时(可选,根据需求调整)
  // 自定义缓存键:基于文件修改时间,文件更新时自动失效缓存
  cacheKey: async () => {
    const stats = await fs.stat(path.join(distFolder, 'user', 'index.html'));
    return stats.mtime.toString();
  }
});

// 接口使用缓存后的函数
server.get('/user', async (req, res) => {
  try {
    const htmlContent = await memoizedReadUserPage();
    res.setHeader('Content-Type', 'text/html');
    res.send(htmlContent);
  } catch (error) {
    res.status(500).send('加载用户页面失败');
  }
});

注意事项

  • 如果目标文件会频繁修改,建议添加文件监听(fs.watch),当文件变化时主动清空缓存,避免返回旧内容
  • 手动缓存更轻量化,适合简单场景;memoizee功能更丰富,适合复杂缓存需求
  • Express的sendFile本身有基础优化,但每次请求仍会触发磁盘读取,内存缓存能显著降低IO开销,提升响应速度

内容的提问来源于stack exchange,提问作者user19652820

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:45:34