3
\$\begingroup\$

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);
\$\endgroup\$
  • \$\begingroup\$ You could just import express. blog.modulus.io/nodejs-and-express-static-content \$\endgroup\$ – PatrickS Mar 29 '16 at 11:17
  • 1
    \$\begingroup\$ What is your question exactly? \$\endgroup\$ – A. Romeu Mar 29 '16 at 11:34
  • \$\begingroup\$ @PatrickS I didn't wanna use express here since I am developing an Electron app and I feel like it's too heavy for a simple static file server. \$\endgroup\$ – bool3max Mar 29 '16 at 17:26
3
\$\begingroup\$

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(<path>), 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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.