Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/handler.js
Original file line number Diff line number Diff line change
@@ -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 };
11 changes: 11 additions & 0 deletions src/router.js
Original file line number Diff line number Diff line change
@@ -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;
9 changes: 9 additions & 0 deletions src/server.js
Original file line number Diff line number Diff line change
@@ -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!"
);
});