Node.js 自带的 http 模块来实现一个简单的本地服务器

1.创建一个 server.js 文件:

复制代码
const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  // 获取请求的文件路径
  const filePath = path.join(__dirname, 'dist', req.url);
  
  // 读取文件内容并返回给客户端
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('Not Found');
    } else {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(data);
    }
  });
});

const port = 3000;
server.listen(port, () => {
  console.log(`Server is running at http://127.0.0.1:${port}`);
});

node server.js

相关推荐
钛态1 分钟前
Flutter for OpenHarmony:mockito 单元测试的替身演员,轻松模拟复杂依赖(测试驱动开发必备) 深度解析与鸿蒙适配指南
服务器·驱动开发·安全·flutter·华为·单元测试·harmonyos
%小农25 分钟前
在cursor中使用server
网络·网络协议·http
硅基导游1 小时前
Linux内核观测与跟踪的利器BPF环境测试
linux·服务器·性能监控·bpf
我是谁??2 小时前
在 Rocky Linux 9 无桌面环境中通过 SSH 安装 KVM 虚拟机(Rocky9含 XFCE 桌面/xubuntu20)完整指南
linux·服务器·ssh
西红市杰出青年3 小时前
MCP 的三种数据传输模式教程(stdio / SSE / Streamable HTTP)
网络·网络协议·http·ai
.select.3 小时前
HTTPS 如何优化?
网络协议·http·https
Luke Ewin3 小时前
Linux中部署Qwen3.5大模型
linux·运维·服务器·ai·llm·qwen3.5
春日见3 小时前
云服务器开发与SSH
运维·服务器·人工智能·windows·git·自动驾驶·ssh
minji...3 小时前
Linux 进程间通信(三)命名管道
linux·服务器·网络