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

相关推荐
AI木马人7 分钟前
3.【Prompt工程实战】如何设计一个可复用的Prompt系统?(避免每次手写提示词)
linux·服务器·人工智能·深度学习·prompt
挽安学长1 小时前
保姆级教程,通过GACCode使用Claude Code Desktop!
运维·服务器
firstacui2 小时前
MGRE实验
运维·服务器·网络
大卡片3 小时前
IO模型与并发服务器设计
运维·服务器·网络
莎士比亚的文学花园3 小时前
Linux驱动开发(1)——系统移植
linux·运维·服务器
PH = 73 小时前
OverlayFS联合文件系统使用示例
java·linux·服务器
志栋智能4 小时前
超自动化巡检:解锁运维数据的深层价值
运维·服务器·数据库·自动化
坚持就完事了5 小时前
Linux中的mv命令
linux·运维·服务器
SongYuLong的博客5 小时前
Claude Code安装配置(Linux)
linux·运维·服务器
zhensherlock5 小时前
Protocol Launcher 系列:Tally 快速计数器的深度集成
前端·javascript·typescript·node.js·自动化·github·js