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

相关推荐
Mr_li15 小时前
NestJS 集成 TypeORM 的最优解
node.js·nestjs
UIUV17 小时前
node:child_process spawn 模块学习笔记
javascript·后端·node.js
Sinclair17 小时前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
前端付豪2 天前
Nest 项目小实践之注册登陆
前端·node.js·nestjs
Rockbean2 天前
用40行代码搭建自己的无服务器OCR
服务器·python·deepseek
天蓝色的鱼鱼2 天前
Node.js 中间层退潮:从“前端救星”到“成本噩梦”
前端·架构·node.js
codingWhat2 天前
uniapp 多地区、多平台、多环境打包方案
前端·架构·node.js
小p2 天前
nodejs学习: 服务器资源CPU、内存、硬盘
node.js
茶杯梦轩2 天前
CompletableFuture 在 项目实战 中 创建异步任务 的核心优势及使用场景
服务器·后端·面试
Mr_li2 天前
手摸手,教你如何优雅的书写 NestJS 服务配置
node.js·nestjs