Skip to content

Instantly share code, notes, and snippets.

@coolov
Last active February 24, 2020 19:22
Show Gist options
  • Save coolov/22f346ccee9c029fb26a6e04f0ca8bb3 to your computer and use it in GitHub Desktop.
Save coolov/22f346ccee9c029fb26a6e04f0ca8bb3 to your computer and use it in GitHub Desktop.
mnml node server
const fs = require("fs");
const util = require("util");
const http = require("http");
const path = require("path");
const stat = util.promisify(fs.stat);
const port = 8080;
const rootDir = path.join(__dirname, "public");
const mimeTypes = {
".css": "text/css",
".gif": "image/gif",
".html": "text/html",
".js": "application/javascript",
".json": "application/json",
".png": "image/png",
".woff": "font/woff",
".woff2": "font/woff2"
};
// static request listener
async function static(req, res) {
res.on("finish", () => {
console.log(res.statusCode, req.url);
});
try {
let filePath = path.join(rootDir, req.url);
let stats = await stat(filePath);
if (stats.isDirectory()) {
filePath = path.join(rootDir, req.url, "index.html");
stats = await stat(filePath);
}
const modified = new Date(stats.mtime);
const etag = `${stats.ino}-${stats.size}-${modified.getTime()}`;
// conditional requests
if (
(req.headers["if-modified-since"] &&
new Date(req.headers["if-modified-since"]) >= modified) ||
(req.headers["if-none-match"] && req.headers["if-none-match"] === etag)
) {
res.writeHead(304);
res.end();
return;
}
const headers = {
"cache-control": "no-cache",
"content-length": stats.size,
"content-type": mimeTypes[path.extname(filePath)] || "text/plain",
etag,
"last-modified": modified.toUTCString()
};
res.writeHead(200, headers);
fs.createReadStream(filePath).pipe(res);
} catch (err) {
if (err.code === "ENOENT") {
res.writeHead(404);
res.end("404 Not Found!");
} else {
throw err;
}
}
}
// add routes here
async function router(req, res) {
try {
/*
if you want to serve everything but js files from /index.html
useful when the routing is on the front end (aka spa)!
*/
// if (!req.url.endsWith("js")) {
// req.url = "/";
// }
static(req, res);
} catch (err) {
console.error(err);
res.writeHead(500);
res.end("500 Internal Server Error!");
}
}
http.createServer(router).listen(port, () => {
console.log("Port:", port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment