主代码index.js
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");
}
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.readFile(filePath, (err, data) => {if (err) {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
{"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"}
}