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

相关推荐
先知后行。3 小时前
Liunx驱动 IO 模型
linux·运维·服务器
计算机安禾3 小时前
【Linux从入门到精通】第39篇:版本控制Git服务器搭建——Gitea/GitLab私有化部署
linux·服务器·git
橙子也要努力变强4 小时前
volatile与信号
linux·服务器·c++
lifewange4 小时前
Node.js安装步骤
node.js
Lucky_Turtle5 小时前
【Linux】debain13开启bbr
服务器·azure
时寒的笔记5 小时前
某陆飞11期_webpack案例
前端·webpack·node.js
行者-全栈开发5 小时前
Linux 核弹级高危漏洞 CVE-2026-31431 完整修复指南
linux·运维·服务器·ci/cd·devops·cve·核弹级高危漏洞
春蕾夏荷_7282977255 小时前
1、c++ acl udp服务器客户端简单实例-服务器端(1)
服务器·c++·udp
七七powerful5 小时前
AI+运维提效--HTTPS 证书有效期监控方案
网络协议·http·https