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

相关推荐
SEO-狼术12 小时前
Support Network Diagnostics in .NET
运维·服务器·网络
AI周红伟12 小时前
AI自动盯盘与定时行情分析:OpenClaw股票辅助Agent集成完整使用指南-周红伟
运维·服务器·人工智能·音视频·火山引擎
SPC的存折13 小时前
8、Ansible之Playbook---Roles
linux·服务器·ansible
爱学习的小囧13 小时前
VCF 9.0+Harbor 搭建私有 AI 模型仓库(PAIS)超详细教程
服务器·人工智能·虚拟化·esxi8.0
春日见14 小时前
Tool文件夹:瑞士军刀库
运维·服务器·windows·深度学习·自动驾驶
Gofarlic_OMS14 小时前
SolidEdge专业许可证管理工具选型关键评估标准
java·大数据·运维·服务器·人工智能
萝卜白菜。15 小时前
TongWeb7.0 集中管理heimdall配置文件说明
linux·运维·服务器
ji_shuke16 小时前
CloudFront 跨域问题(CORS)的几种解决方式
服务器·cloudfront
IMPYLH16 小时前
Linux 的 install 命令
linux·运维·服务器·bash
寻道模式16 小时前
【运维心得】“龙虾”非本地访问的坑
运维·服务器