1
\$\begingroup\$

Here is the code:

var http = require("http");
var fs = require("fs");
var path = require("path");
var ip = require("request-ip");

var hostname = "localhost";
var port = 3001;

const logs = {};

http.createServer ( function(req, res) {

    addLog(req);

    console.clear();
    console.log(logsToString());

    if (req.method.toLowerCase() === "get"){
        if (req.url === "/"){
            pipeToRes(res,200,  "text/html", "./public/index.html", "utf-8");
        } else if (req.url.match(/.css$/)){
            pipeToRes(res, 200, "text/css", path.join(__dirname, "public", req.url), "utf-8");
        } else if (req.url.match(/.js$/)){
            pipeToRes(res, 200, "application/javascript", path.join(__dirname, "public", req.url), "utf-8");
        } else if (req.url.match(/.ttf$/)){
            pipeToRes(res, 200, "application/octet-stream", path.join(__dirname, "public", req.url), "");
        } else if (req.url.match(/.ico$/)){
            pipeToRes(res, 200, "image/ico", path.join(__dirname, "public", req.url), "");
        } else {
            fillRes(res, 404, "text/plain", "404: File Not Found");
        }
    } else{
        let body = [];

        req.on("data", function(chunk){
            body.push(chunk);
        });
        req.on("end", function(){
            body = Buffer.concat(body).toString();
            fillRes(res, 405, "text/plain", `Request Body: ${body}\n\n `+"405: Method Not Allowed: This server \
            does not require any information from you, but only responds to GET requests by serving back to \
            the client the web files (HTML, CSS, JS, Image Files, icons, Videos, e.t.c..) to view them on the \
            browser.");
        });


    }

}).listen(port);


console.log(`Server ${hostname} is listening on port ${port}`);


function addLog(req){
    var thisIP = ip.getClientIp(req)
    if (logs[thisIP] != undefined){
        logs[thisIP].push({"method": req.method, "url": req.url});
    } else {
        logs[thisIP] = [{"method": req.method, "url": req.url}];
    }
}

function logsToString(){
    var formatted = "----------------\nCURRENT LOGS\n----------------\n\n";

    for (var clientIp in logs){
        formatted += "\nFROM IP ("+clientIp+"):"
        var clientLogs = logs[clientIp];

        for (var i = 0; i < clientLogs.length; i++){
            var thisLog = clientLogs[i];
            formatted += "\n\t- Recieved "+thisLog["method"]+" request for "+thisLog["url"]
        }
    }

    return formatted;
}

function fillRes(res, responseCode, mimeType, data){
    res.writeHead(responseCode, {"Content-Type": mimeType});

    res.end(data);
}

function  pipeToRes(res, responseCode, mimeType, pathParam, readAs){
    res.writeHead(responseCode, {"Content-Type": mimeType});

    fs.createReadStream(pathParam, readAs).pipe(res);
}

Points I am interested in:

  • Is using the functions fillRes and pipeToRes a good choice rather than repeating res.writeHead ... res.end()
  • What about their names? The semantics of fillRes is that basically you are manipulating the response object passed to you by http.createServer, as in you are "filling" the response write stream. is something like writeResponse or writeRes better?
  • What do you think about the technique used to log the requests? Each time a request is received, the server checks if this specific IP has requested before and then groups all his request in a list. A dictionary called logs stores all these requests, where the IP is the key, and the value is a list of all the requests from that IP.
  • Anything else? What should I improve? Please remember that I am a total newbie, and all help is really honestly greatly appreciated.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.