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

相关推荐
暴力求解4 小时前
Linux---保存信号
linux·运维·服务器·开发语言·操作系统
bqq198610265 小时前
Ubuntu vs CentOS
linux·服务器
雨声不在5 小时前
linux Copy Fail
linux·服务器
RunningBComeOn6 小时前
为什么无法抓取到http之间的明文传输
网络·网络协议·http
Gary Studio6 小时前
Selinux编写
linux·服务器·前端
Danileaf_Guo6 小时前
手搓KVM虚拟化!Ubuntu 26.04 + KVM 7.0.0,告别VMware的低成本玩法
linux·运维·服务器·ubuntu
网络点点滴6 小时前
NPM的包版本管理
前端·npm·node.js
中海德--陈顺真6 小时前
HONEYWELL 扫描架控制板 51000398
运维·服务器·人工智能
lbb 小魔仙6 小时前
2026远程办公软件夏季深度横测:ToDesk、向日葵、网易UU远程全面对比,远控白皮书
android·服务器·网络协议·tcp/ip·postgresql
嵌入式×边缘AI:打怪升级日志6 小时前
全志T113 Tina-Linux开发环境搭建:从安装依赖到打包烧录完整教程
linux·运维·服务器