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

相关推荐
仙柒41521 小时前
管理网络安全
linux·运维·服务器
isyangli_blog21 小时前
静态网站部署方案
服务器
大家的林语冰1 天前
Node 2026 发布,JS 三大新功能上线,最后一个奇偶版本
前端·javascript·node.js
189228048611 天前
NV243美光MT29F32T08GWLBHD6-24QJES:B
大数据·服务器·人工智能·科技·缓存
洋哥网络科技1 天前
centos7 升级openssh-10.2
linux·运维·服务器·系统安全
IpdataCloud1 天前
企业级IP定位服务准确率怎么保证?从数据源到离线库的精度提升指南
运维·服务器·网络·数据库·tcp/ip
treesforest1 天前
从IP地址归属地查询到IP地理位置精准查询指南
服务器·前端·网络
Aolith1 天前
从裸奔到加固:我的校园论坛网络安全实战
node.js·全栈
IT大白鼠1 天前
Linux账号和权限管理
linux·运维·服务器
Summer不秃1 天前
深入理解 Token 无感刷新:从并发雪崩到单例锁 + 请求队列的完整实现
前端·http