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 天前
同步服务器时间
运维·服务器
_F_y1 天前
Linux:多线程
linux·运维·服务器
Ha_To1 天前
2025.12.18 NAT地址转换、PAT
linux·服务器·网络
vortex51 天前
Linux 命令行入门:命令的构成与选项用法
linux·运维·服务器
vipbic1 天前
Strapi 5 怎么用才够爽?这款插件带你实现“建站自由”
后端·node.js
山风wind1 天前
网络分层模型:OSI和TCP/IP参考模型
服务器·网络·tcp/ip
像风一样的男人@1 天前
linux --防火墙
linux·运维·服务器
skywalk81631 天前
使用Trae 自动编程:为小学生学汉语项目增加不同出版社教材的区分
服务器·前端·人工智能·trae
趴在窗边数星星1 天前
Koa 源码深度解析:带你理解 Koa 的设计哲学和核心实现原理
node.js
网硕互联的小客服1 天前
Centos系统如何更改root账户用户名?需要注意什么?
linux·运维·服务器·数据库·安全