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

使用Node.js原生http模块实现无需重启的本地HTML静态服务

问题原因

你最初的代码存在缓存问题,本质是在服务启动阶段就一次性将HTML文件内容读入内存存储到index变量中,后续所有请求都会直接返回内存里的旧内容,自然不会响应磁盘上的文件改动。而express的sendFile方法是每次收到请求时,才会读取磁盘上的最新文件内容返回,因此不需要重启服务。

原生http模块实现方案

只需要把文件读取逻辑移动到请求回调函数内部,每次收到请求时再读取最新的文件即可,参考代码如下:

var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function (req, res) {
  // 仅处理根路径请求,可根据需求扩展路由
  if (req.url === '/') {
    // 每次请求都读取磁盘上的最新文件
    fs.readFile(path.join(__dirname, 'index.html'), 'utf8', function (err, data) {
      if (err) {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        res.end('404 Not Found');
        return;
      }
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end(data);
    });
    return;
  }
  res.writeHead(404, {'Content-Type': 'text/plain'});
  res.end('404 Not Found');
}).listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

可选优化

如果需要提升响应性能,可以增加缓存校验逻辑:读取文件时获取文件的最后修改时间,响应时返回Last-Modified头,下次请求时校验请求头中的If-Modified-Since,如果文件没有改动直接返回304状态码,不需要重复传输文件内容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:45:05