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

相关推荐
Amy_au5 分钟前
Linux week 01
linux·运维·服务器
淮上安子骞18 分钟前
sage10.8源码部署
服务器·密码学·ctf·本地部署·sage
KingRumn21 分钟前
DBUS源码剖析之DBusMessage数据结构
linux·服务器·数据结构
OpenMiniServer1 小时前
JsonKV协议技术文档
linux·服务器·网络
小鹏linux1 小时前
【linux】进程与服务管理命令 - chkconfig
linux·运维·服务器
莓有烦恼吖1 小时前
基于AI图像识别与智能推荐的校园食堂评价系统研究 05-审核机制模块
java·服务器·python
闻道且行之3 小时前
Linux|CUDA与cuDNN下载安装全指南:默认/指定路径双方案+多CUDA环境一键切换
linux·运维·服务器
Ahtacca3 小时前
Linux环境下前后端分离项目(Spring Boot + Vue)手动部署全流程指南
linux·运维·服务器·vue.js·spring boot·笔记
_w_z_j_3 小时前
Linux----Socket编程基础
linux·运维·服务器
xdpcxq10294 小时前
风控场景下超高并发频次计算服务
java·服务器·网络