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"
  }
}
相关推荐
浪前1 分钟前
【网络篇】从零写UDP客户端/服务器:回显程序源码解析
服务器·网络·udp
layman052815 分钟前
node.js 实战——(fs模块 知识点学习)
javascript·node.js
毕小宝16 分钟前
编写一个网页版的音频播放器,AI 加持,So easy!
前端·javascript
万水千山走遍TML16 分钟前
JavaScript性能优化
开发语言·前端·javascript·性能优化·js·js性能
Aphasia31116 分钟前
react必备JS知识点(一)——判断this指向👆🏻
前端·javascript·react.js
会飞的鱼先生32 分钟前
vue3中slot(插槽)的详细使用
前端·javascript·vue.js
亚力山大抵1 小时前
实验2 python的TCP群聊系统实现
服务器·python·tcp/ip
bing_1581 小时前
一个 HTTP 请求进入 Spring MVC 应用后,大致经历了哪些主要步骤?
spring·http·mvc
佩奇的技术笔记1 小时前
Java学习手册:HTTP 协议基础知识
java·http
知心宝贝1 小时前
🔍 从简单到复杂:JavaScript 事件处理的全方位解读
前端·javascript·面试