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

相关推荐
克莱因3582 小时前
Linux CentOS7 进程基础知识
linux·运维·服务器
Skilce2 小时前
ZrLog 高可用部署
运维·服务器·数据库·阿里云·maven
我爱学习好爱好爱5 小时前
Ansible 常用模块详解:yum、service/systemd、copy实战
linux·服务器·ansible
papaofdoudou5 小时前
LINUX VFIO被IOMMUFD取代
linux·运维·服务器
平生不喜凡桃李6 小时前
浅谈 Linux 中 namespace 相关系统调用
java·linux·服务器
虾..7 小时前
多路复用 --- select系统调用
服务器·数据库·sql
杨云龙UP7 小时前
mysqldump逻辑备份文件恢复总结:全库恢复、单库恢复,一篇讲明白
linux·运维·服务器·数据库·mysql·adb
舰长1157 小时前
linux系统服务器加固1、中风险 未设置登录失败处理功能和登录连接超时处理功能。2、中风险 未限制默认账户的访问权限。3、中风险 未实现管理用户的权限分离。
linux·运维·服务器
mounter6258 小时前
Linux 7.0 重磅更新:详解 nullfs 如何重塑根文件系统挂载与内核线程隔离
linux·运维·服务器·kernel
左手厨刀右手茼蒿9 小时前
Flutter 组件 http_requests 适配鸿蒙 HarmonyOS 实战:极简网络请求,构建边缘端轻量级 RESTful 通讯架构
网络·flutter·http