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

相关推荐
昭昭日月明17 小时前
搭建高可用私有 NPM 镜像
node.js·代码规范
七牛云行业应用1 天前
保姆级 OpenClaw 避坑指南:手把手教你看日志修 Bug,顺畅连通各大 AI 模型
人工智能·后端·node.js
牛奶1 天前
从一行字到改变世界:HTTP这三十年都经历了什么?
前端·http·http3
多厘1 天前
使用 nvm 管理多版本 Node 项目依赖
node.js
牛奶1 天前
浏览器到底在偷偷帮你做什么?——HTTP缓存与刷新机制
前端·http·浏览器
前端双越老师2 天前
Skills 是什么?如何用于 Agent 开发?
人工智能·node.js·agent
San303 天前
AI 时代的“USB-C”接口:MCP 核心原理与实战
langchain·node.js·mcp
韭菜炒大葱3 天前
前端经典面试题:从 URL 输入到页面展示,中间经历了什么?
前端·http·面试
helloweilei4 天前
javascript 结构化克隆
javascript·node.js
小蜜蜂dry5 天前
nestjs学习 - 控制器、提供者、模块
前端·node.js·nestjs