I bet everyone who tried node, has written that famous sample server code which appears in nodejs.org homepage. Then without a blink most of us moved to express or some other node framework, with or without knowing what's happening under the hood. Well, for educational purposes I wrote a simple node server without using any npm module. For anyone who is interested in what's happening behind the scene, this would be a great starting point.
var http = require("http"),
fs = require("fs"),
path = require("path");
switch(extName) {
case ".html": {
contentType = "text/html";
dirPath = "/public/views/";
} break;
case ".css": {
contentType = "text/css";
dirPath = "/public/css/";
} break;
case ".js": {
contentType = "text/javascript";
dirPath = "/public/js/";
} break;
}
fs.exists(filePath, function(isExists) {
if(isExists) {
readAndSendFile(res, filePath, contentType,200);
}
else {
redirect404();
}
});
Please find the complete code at github. Please note that there are many ways to improve this and I would recommend to checkout Danial Khosravi's blog on the same topic for improved version.