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

相关推荐
A132470531211 分钟前
防火墙配置入门:保护你的服务器
linux·运维·服务器·网络
離離原上譜25 分钟前
Windows 环境下 Node.js + Claude Code 安装与配置教程
windows·node.js
Zzqqads27 分钟前
vnc连接问题:Timed out waiting for a response from the computer
服务器
玖疯子34 分钟前
JavaScript性能优化实战的技术文章大纲
服务器
小鹏linux2 小时前
【linux】进程与服务管理命令 - at
linux·运维·服务器
wniuniu_2 小时前
blob是啥
java·服务器·网络
FIT2CLOUD飞致云2 小时前
操作教程丨通过1Panel轻松安装和管理MySQL开源数据库
linux·运维·服务器·mysql·开源·1panel
222you2 小时前
前后端分离项目在云服务器上的部署(Spring Boot + Vue)
运维·服务器·spring boot
QT 小鲜肉2 小时前
【Linux命令大全】001.文件管理之lsattr命令(实操篇)
linux·运维·服务器·笔记·elasticsearch
郝学胜-神的一滴3 小时前
Linux线程错误调试指南:从原理到实践
linux·服务器·开发语言·c++·程序人生