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

相关推荐
青禾8375 小时前
Linux 操作系统入门指南:从目录结构到常用命令
linux·运维·服务器
zhengqweasd6 小时前
流量没跑满、带宽空闲,业务依然卡顿
运维·服务器·网络
M哥支付7 小时前
高频交易优选方案:银联快捷支付通道
服务器·网络·其他·微信·金融
稳联技术老娜8 小时前
伺服内嵌EtherNet IP方案:嵌入式小板SPI通讯固件Demo程序适配改造
运维·服务器·网络
en.en..8 小时前
Linux系统编程:fcntl 与 ioctl
linux·运维·服务器
会周易的程序员9 小时前
5Draft(五帝)测试报告
服务器·c++·分布式·raft·共识算法·共识·算力服务器
一技安身10 小时前
【信创】外网aarch64终端安装deepseek Ragflow 迁移至内网银河麒麟服务器
运维·服务器
M哥支付11 小时前
快捷支付 VS 网关支付 安全对比
服务器·网络·其他·微信·金融
2501_9289962211 小时前
Agent 开发的 API 选型:从 Function Calling 到多模型协作的中科热备底层逻辑
服务器·重构·gitlab
非凡ghost12 小时前
AI修图不“造假“,摄影师的出片效率加速器
服务器·前端·人工智能·电脑