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

相关推荐
@encryption40 分钟前
TCP,IP
服务器·网络·tcp/ip
十五年专注C++开发1 小时前
libuv:一个跨平台的C++异步 I/O 库
开发语言·c++·node.js·libuv·vlibuv
亚林瓜子1 小时前
linux账号强制密码过期导致私钥文件登录异常问题——(current) UNIX password:
linux·运维·服务器·ssh·aws·ec2·chage
LXY_BUAA1 小时前
《嵌入式操作系统》_驱动框架_20260318
linux·运维·服务器
困惑阿三2 小时前
客户消息及时反馈
nginx·node.js·飞书·企业微信
sdm0704272 小时前
Linux-进程2
运维·服务器
zzzsde3 小时前
【Linux】进程控制(1):进程创建&&进程终止
linux·运维·服务器
sugar__salt3 小时前
网络原理(五)——HTTP
网络·网络协议·http
饥饿的帕尼尼3 小时前
Claude Code本地安装使用教程
node.js·github·claude
开源盛世!!4 小时前
3.19-3.21
linux·服务器·前端