HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

NodeJS static file HTTP server

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filenodejshttpserverstatic

Problem

I wrote a NodeJS HTTP server specifically for serving static files. I didn't bother much about security since the server is going to be used locally in my Electron application.

function buildStaticServer() {
    const fs = require("fs");
    const urlModule = require("url");
    return require("http").createServer(function(req, res) {
        var parsedUrl = urlModule.parse(req.url, true);
        var completePath = __dirname + parsedUrl.pathname;
        console.log(completePath);
        fs.stat(completePath, function(err, statObj){
            //we first check if the pathName exists
            if(err){
                res.writeHead(404);
                return res.end("404 Directory not found");
            }
            if(statObj.isDirectory()){
                //if the pathname is a directory, we're gonna try to send the index.html in that directory
                fs.readFile(completePath + "/index.html", function(err, data){
                    if(err){
                        res.writeHead(404);
                        return res.end("404 File Corrupt or Not Found");
                    }
                    res.writeHead(200);
                    res.write(data);
                    return res.end();                   
                })
            }
            fs.readFile(completePath, function(err, data){
                if(err){
                    res.writeHead(404);
                    res.end("404 File Corrupt or Not Found");
                    return;
                }
                res.writeHead(200);
                res.write(data);
                return res.end();
            })
        }); 
    });
}
var staticServer = buildStaticServer().listen(9000);

Solution

There are more efficient ways to do this. Now you are buffering the whole file content into memory, when you perform fs.readFile(...). I recommend that you use a readStream, that for example using fs.createReadStream(), pipe it into res. This way you will begin sending the file content earlier, and stop wasting your node processes memory. Also consider moving require to the top of your code, it is a bad practice to call require from function body.

Context

StackExchange Code Review Q#124166, answer score: 4

Revisions (0)

No revisions yet.