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"
  }
}
相关推荐
咖啡の猫22 分钟前
JavaScript基础-创建对象的三种方式
开发语言·javascript·ecmascript
outstanding木槿40 分钟前
react中安装依赖时的问题 【集合】
前端·javascript·react.js·node.js
IP管家1 小时前
企业级IP代理解决方案:负载均衡与API接口集成实践
服务器·网络·数据库·网络协议·tcp/ip·容器·负载均衡
愚润求学1 小时前
【Linux】进程间通信(一):认识管道
linux·运维·服务器·开发语言·c++·笔记
小吕学编程1 小时前
Jackson使用详解
java·javascript·数据库·json
霸王蟹1 小时前
React中useState中更新是同步的还是异步的?
前端·javascript·笔记·学习·react.js·前端框架
霸王蟹1 小时前
React Hooks 必须在组件最顶层调用的原因解析
前端·javascript·笔记·学习·react.js
{⌐■_■}1 小时前
【gRPC】HTTP/2协议,HTTP/1.x中线头阻塞问题由来,及HTTP/2中的解决方案,RPC、Protobuf、HTTP/2 的关系及核心知识点汇总
网络·网络协议·计算机网络·http·rpc·golang
专注VB编程开发20年2 小时前
asp.net IHttpHandler 对分块传输编码的支持,IIs web服务器后端技术
服务器·前端·asp.net
光不度AoKaNa2 小时前
计算机操作系统概要
linux·运维·服务器