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

相关推荐
Lost_in_the_woods9 分钟前
Java程序员的Linux之路——命令篇
linux·运维·服务器
IpdataCloud9 分钟前
在线IP查询API与本地离线库,速度与安全如何选型?
运维·服务器·网络
困惑阿三14 分钟前
全栈服务器运维终极备忘录
运维·服务器·nginx·pm2
小庄梦蝶14 分钟前
Mixed Content: The page at ‘https://域名/‘ was loaded over HTTPS
网络协议·http·https
带娃的IT创业者22 分钟前
Weclaw 混合通讯架构实战:HTTP+SSE+WebSocket的三元融合如何支撑起整个 AI 助手的实时对话?
websocket·http·fastapi·sse·流式响应·实时通讯·混合架构
optimistic_chen22 分钟前
【Vue3入门】自定义指令与插槽详解
linux·运维·服务器·vue.js·前端框架·指令
牛奶咖啡1331 分钟前
基于Cobbler的系统自动化安装部署——Cobbler的安装部署实践
linux·运维·服务器·cobbler·cobbler的安装配置·cobbler环境检查问题解决·cobbler中导入系统镜像
mounter62534 分钟前
深度解析 RDMA 技术的里程碑:基于 DMA-BUF 的 P2P 直接访问(GPU Direct RDMA 新姿势)
linux·运维·服务器·网络·p2p·kernel
李白的天不白1 小时前
linux安装MongoDB
linux·运维·服务器
BioRunYiXue1 小时前
从现象到机制:蛋白降解调控研究的系统策略与实验设计
java·linux·运维·服务器·网络·人工智能·eclipse