Skip to content

Instantly share code, notes, and snippets.

@cornellb28
Forked from prof3ssorSt3v3/index.html
Created November 10, 2020 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cornellb28/50bb7251132c08d01a7c71fe8f797d49 to your computer and use it in GitHub Desktop.
Save cornellb28/50bb7251132c08d01a7c71fe8f797d49 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Server</title>
<link rel="stylesheet" href="./main.css" />
</head>
<body>
<h1>This is a sample HTML file for testing the static file server.</h1>
<script src="./main.js"></script>
</body>
</html>
html {
padding: 0;
margin: 0;
box-sizing: border-box;
font-size: 20px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
font-weight: 300;
line-height: 1.7;
}
body {
color: gold;
}
document.addEventListener("DOMContentLoaded", () => {
//sample JS file beinig sent to the server
setTimeout(() => {
document.body.style.color = "rebeccapurple";
}, 2000);
});
//Create a server that can send back static files
const http = require("http");
const url = require("url");
const fs = require("fs");
//npm i mime-types
const lookup = require("mime-types").lookup;
const server = http.createServer((req, res) => {
//handle the request and send back a static file
//from a folder called `public`
let parsedURL = url.parse(req.url, true);
//remove the leading and trailing slashes
let path = parsedURL.path.replace(/^\/+|\/+$/g, "");
/**
* /
* /index.html
*
* /main.css
* /main.js
*/
if (path == "") {
path = "index.html";
}
console.log(`Requested path ${path} `);
let file = __dirname + "/public/" + path;
//async read file function uses callback
fs.readFile(file, function(err, content) {
if (err) {
console.log(`File Not Found ${file}`);
res.writeHead(404);
res.end();
} else {
//specify the content type in the response
console.log(`Returning ${path}`);
res.setHeader("X-Content-Type-Options", "nosniff");
let mime = lookup(path);
res.writeHead(200, { "Content-type": mime });
// switch (path) {
// case "main.css":
// res.writeHead(200, { "Content-type": "text/css" });
// break;
// case "main.js":
// res.writeHead(200, { "Content-type": "application/javascript" });
// break;
// case "index.html":
// res.writeHead(200, { "Content-type": "text/html" });
// }
res.end(content);
}
});
});
server.listen(1234, "localhost", () => {
console.log("Listening on port 1234");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment