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) {
  let filePath = req.url === "/" ? "/index.html" : req.url; // add index.html 
  filePath = path.join(__dirname, filePath);                // get the absolute path to the file 

  let ext = path.extname(filePath);                         // get the file extension
  let contentType = mimeTypes[ext]                          // lookup content type based on ext
                         ||  "application/octet-stream";    // if not there, treat as download

  fs.readFile(filePath, (err, data) => {                    // read file, set data to contents
    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 and the data
    res.end(data);
  });
}

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