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"
  }
}
相关推荐
小高0071 小时前
🌐ES6 这 8 个隐藏外挂,知道 3 个算我输!
前端·javascript·面试
东坡白菜1 小时前
SSE 实现 AI 对话中的流式输出
javascript·vue.js
小桥风满袖2 小时前
极简三分钟ES6 - ES9中字符串扩展
前端·javascript
前端人类学2 小时前
掌控异步洪流:多请求并发下的顺序控制艺术
javascript·promise
CryptoRzz3 小时前
印度尼西亚股票数据API对接实现
javascript·后端
lecepin4 小时前
AI Coding 资讯 2025-09-17
前端·javascript·面试
猩兵哥哥5 小时前
前端面向对象设计原则运用 - 策略模式
前端·javascript·vue.js
江城开朗的豌豆5 小时前
解密React虚拟DOM:我的高效渲染秘诀 🚀
前端·javascript·react.js
江城开朗的豌豆5 小时前
React应用优化指南:让我的项目性能“起飞”✨
前端·javascript·react.js
Asort6 小时前
JavaScript 从零开始(六):控制流语句详解——让代码拥有决策与重复能力
前端·javascript