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"
  }
}
相关推荐
网硕互联的小客服8 分钟前
Centos系统如何更改root账户用户名?需要注意什么?
linux·运维·服务器·数据库·安全
柒.梧.16 分钟前
HTML入门指南:30分钟掌握网页基础
前端·javascript·html
wunianor26 分钟前
[高并发服务器]DEBUG日志
linux·运维·服务器·c++
智算菩萨1 小时前
实战:高级中文自然语言处理系统的Python设计与实现
前端·javascript·easyui
lx7416026981 小时前
百度网盘bypy使用
服务器
为什么不问问神奇的海螺呢丶2 小时前
服务器巡检报告-基于categraf 采集数据-存入Prometheus-写入mysql后生成报告
服务器·mysql·prometheus
网硕互联的小客服2 小时前
遇到网站500内部服务器错误如何处理?如何预防这样的问题发生?
运维·服务器·安全
幼儿园老大2 小时前
告别代码屎山!UniApp + Vue3 自动化规范:ESLint 9+ 扁平化配置全指南
javascript·vue.js
小阿宁的猫猫2 小时前
CSRF漏洞的原理、防御和比赛中的运用
安全·http·xss·csrf
Liu.7742 小时前
vue3组件之间传输数据
前端·javascript·vue.js