Thursday, January 29, 2015

Simple Pure Node Server

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.

Following are the core modules used. "http" module for server creation, "fs" module for read static content from the disk and "path" module for work with file paths.

var http = require("http"),
    fs = require("fs"),
    path = require("path");

Static files are filtered using simple switch statement.

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;
}    
If requested file is available on the disk, read and send the response. If not redirect to the error page.

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.

No comments:

Post a Comment