From d9d732c305dab5cbc5ca866e2147b135c9b6b38c Mon Sep 17 00:00:00 2001 From: wajdomahdi Date: Thu, 11 Jul 2019 23:35:11 +0300 Subject: [PATCH] add handler & router & server files --- src/handler.js | 43 +++++++++++++++++++++++++++++++++++++++++++ src/router.js | 11 +++++++++++ src/server.js | 9 +++++++++ 3 files changed, 63 insertions(+) create mode 100644 src/handler.js create mode 100644 src/router.js create mode 100644 src/server.js diff --git a/src/handler.js b/src/handler.js new file mode 100644 index 00000000..569949c8 --- /dev/null +++ b/src/handler.js @@ -0,0 +1,43 @@ +const fs = require("fs"); +const path = require("path"); +const homeHandler = (request, response) => { + const filePath = path.join(__dirname, "../public/index.html"); + fs.readFile(filePath, (error, file) => { + if (error) { + return console.log(error); + + response.writeHead(500, { "Content-Type": "text/html" }); + response.end("server error"); + } else { + response.writeHead(200, { + "Content-Type": "text/html" + }); + response.end(file); + } + }); +}; + +const publicHandler = (request, response, endpoint) => { + const extinsion = endpoint.split(".")[1]; + const extinsionType = { + html: "text/html", + css: "text/css", + js: "application/javascript", + jpg: "image/jpg", + ico: "image/x-icon" + }; + + const filePath = path.join(__dirname, "/../public", endpoint); + fs.readFile(filePath, (error, file) => { + if (error) { + response.writeHead(500, { "Content-Type": "text/html" }); + response.end("server error"); + } else { + response.writeHead(200, { + "Content-Type": extinsionType[extinsion] + }); + response.end(file); + } + }); +}; +module.exports = { homeHandler, publicHandler }; diff --git a/src/router.js b/src/router.js new file mode 100644 index 00000000..0e4877af --- /dev/null +++ b/src/router.js @@ -0,0 +1,11 @@ +const { homeHandler, publicHandler } = require("./handler"); +const router = (request, response) => { + const endpoint = request.url; + if (endpoint === "/") { + homeHandler(request, response); + } else if (endpoint.split(".")[1]) { + publicHandler(request, response, endpoint); + } +}; + +module.exports = router; diff --git a/src/server.js b/src/server.js new file mode 100644 index 00000000..1370563b --- /dev/null +++ b/src/server.js @@ -0,0 +1,9 @@ +const http = require("http"); +const router = require("./router"); +const server = http.createServer(router); + +server.listen(3000, () => { + console.log( + "Server is listening on http://localhost:3000. Ready to accept requests!" + ); +});