console.time('start WebServer need time');
const libHttp = require('http');
const libUrl = require('url');
const libFs = require("fs");
const libPath = require("path");
var funGetContentType = function (filePath) {
let contentType = "";
let ext = libPath.extname(filePath);
switch (ext) {
case ".html":
contentType = "text/html";
break;
case ".htm":
contentType = "text/html";
break;
case ".js":
contentType = "text/javascript";
break;
case ".css":
contentType = "text/css";
break;
case ".gif":
contentType = "image/gif";
break;
case ".jpg":
contentType = "image/jpeg";
break;
case ".png":
contentType = "image/png";
break;
case ".ico":
contentType = "image/icon";
break;
default:
contentType = "application/octet-stream";
}
return contentType;
}
const funWebSvr = function (req, res) {
let reqUrl = req.url;
console.log(reqUrl);
let pathName = libUrl.parse(reqUrl).pathname;
if (libPath.extname(pathName) === "") {
pathName += "/";
}
if (pathName.charAt(pathName.length - 1) === "/") {
pathName += "index.html";
}
let filePath = libPath.join("./", pathName);
libFs.exists(filePath, function (exists) {
if (exists) {
res.writeHead(200, { "Content-Type": funGetContentType(filePath) });
let stream = libFs.createReadStream(filePath, { flags: "r", encoding: null });
stream.on("error", function () {
res.writeHead(404);
res.end("<h1>404 Read Error</h1>");
});
stream.pipe(res);
}
else {
res.writeHead(404, { "Content-Type": "text/html" });
res.end("<h1>404 Not Found</h1>");
}
});
}
const webSvr = libHttp.createServer(funWebSvr);
webSvr.on("error", function (error) {
console.log(error);
});
webSvr.listen(8888, function () {
console.log('WebServer running at http://127.0.0.1:8888/');
console.timeEnd('start WebServer need time');
});