js原生简单办法实现nodejs的HTTP网页服务器,支持配置文件hostconfig.json

主代码index.js

javascript 复制代码
const http = require("http");
const fs = require("fs");
const path = require("path");

// 读取配置文件
let hostconfig;
try {
  hostconfig = JSON.parse(fs.readFileSync("./hostconfig.json", "utf-8"));
} catch (err) {
  console.log(666.909, "hostconfig.json is undefined");
}

// 启动HTTP服务
function startHTTPServer(hostdir) {
  // 初始化服务配置
  const hostcfg = hostconfig.hosts[hostdir];
  if (hostcfg.mimetypes) {
    Object.assign(hostcfg.mimetypes, hostconfig.mimetypes);
  } else {
    hostcfg.mimetypes = hostconfig.mimetypes;
  }
  // 创建服务
  hostcfg.server = http.createServer((req, res) => {
    // 获取请求的文件相对路径
    let filePath = "" + req.url;
    if (filePath == "/" || filePath == "") {
      filePath = "/index.html";
    }
    if (hostdir == "home") {
      filePath = "." + filePath;
    } else {
      filePath = "./" + hostdir + filePath;
    }
    // 使用fs模块读取文件
    fs.readFile(filePath, (err, data) => {
      if (err) {
        // 如果文件不存在或读取错误,返回404状态码
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end(`File Path(${filePath}) not found!`);
        return;
      }
      // 设置响应头,并发送文件内容
      res.writeHead(200, {
        "Content-Type":
          hostcfg.mimetypes[path.extname(filePath)] ||
          "application/octet-stream",
      });
      res.end(data);
    });
  });
  // 启动服务
  hostcfg.server.listen(hostcfg.port, () => {
    console.log(
      `[${hostdir}] Server is running on http://localhost:${hostcfg.port}`
    );
  });
  return hostcfg.server;
}

// 循环启动配置中的服务
Object.keys(hostconfig.hosts).forEach((el) => {
  startHTTPServer(el);
});

配置文件hostconfig.json

javascript 复制代码
{
  "readme": "asai.cc",
  "hosts": {
    "asai": {
      "port": 9090,
      "mimetypes": {}
    },
    "asai.cc/abc": { "port": 9091 }
  },
  "mimetypes": {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "text/javascript",
    ".json": "application/json",
    ".png": "image/png",
    ".jpg": "image/jpeg",
    ".gif": "image/gif",
    ".svg": "image/svg+xml",
    ".txt": "text/plain"
  }
}
相关推荐
猫32813 分钟前
echarts 日常问题解决
前端·javascript·echarts
霸道流氓气质32 分钟前
ApiPost 中配置自动获取 Token 并调用业务接口完整指南
java·服务器·数据库
不简说1 小时前
JS 代码技巧 vol.8 — 20 个函数式编程实战,把 if/else 拍扁的骚操作
前端·javascript·面试
Cobyte2 小时前
模板 DSL 解析器中的状态机设计
前端·javascript·vue.js
无足鸟ICT2 小时前
【RHCA+】查看变量
linux·运维·服务器
IPdodo_2 小时前
Codex 一直显示 Thinking 怎么办?区分任务运行、界面卡住与会话恢复
http·网络调试
Kina_C2 小时前
Linux DNS 服务器-从高速缓存到辅助 DNS 部署指南
linux·运维·服务器·dns
EasyGBS2 小时前
ONVIF设备接入国标GB28181视频平台EasyGBS:不用国标也能一键拉流!
服务器·php·音视频
软件开发技术深度爱好者3 小时前
小学英语单词魔法学园HTML5实现
javascript·html5·英语学习
勉灬之3 小时前
Next.js + Prisma 跨平台部署踩坑记
开发语言·javascript·ecmascript