
const http = require("http");
const fs = require("fs");
const path = require("path");

const PORT = 3000;
const mimeTypes = {
  ".html": "text/html",
  ".css":  "text/css",
  ".js":   "application/javascript",
  ".png":  "image/png",
  ".jpg":  "image/jpeg",
  ".ico":  "image/x-icon"
};

function requestListener(req, res) {
    // add index.html if it was the blank/root request
    let filePath = req.url === "/" ? "/index.html" : req.url; 

    // get the absolute path to the file requested
    filePath = path.join(__dirname, filePath);   

    let ext = path.extname(filePath);    // get the file extension

    // lookup content type based on ext. If not there, treat as a download
    let contentType = mimeTypes[ext] ||  "application/octet-stream";

    // read file, set response data to contents of file 
    fs.readFile(filePath, (err, data) => {       
        if (err) {                               // if error, return 404 Not Found
            res.writeHead(404, { "Content-Type": "text/plain" });
            return res.end("404 Not Found");
        }
        res.writeHead(200, { "Content-Type": contentType }); // otherwise send 200 OK & data
        res.end(data);
    });
}

http.createServer(requestListener).listen(PORT);
console.log(`Server running at http://localhost:${PORT}`);
