Basic HTTP server

I wanted to create a simple and secure HTTP web server.

I used the example found on this question "Basic static file server in NodeJS" and updated / changed some parts here and there.

Here's the code :

var http = require('http'),
    url = require('url'),
    fs = require('fs');

function error404(res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write('404 Not Found\n');
    res.end();
}

http.createServer(function(req, res) {
    var path = url.parse(req.url).pathname.toLowerCase().split('/');
    var file = path[path.length - 1]
    var filename = file.split('.');
    var extension = filename[filename.length - 1];
    if(extension === 'html') {
        fs.exists('./client/' + file, function(exists) {
            if(!exists) { error404(res); }
            else {
                res.writeHead(200, {'Content-Type': 'text/html'});
                var fileStream = fs.createReadStream('./client/' + file);
                fileStream.pipe(res);
                return;
            }
        });
    }
    else if(extension === 'js') {
        fs.exists('./client/js/' + file, function(exists) {
            if(!exists) { error404(res); }
            else {
                res.writeHead(200, {'Content-Type': 'text/javascript'});
                var fileStream = fs.createReadStream('./client/js/' + file);
                fileStream.pipe(res);
                return;
            }
        });
    }
    else if(extension === 'css') {
        fs.exists('./client/css/' + file, function(exists) {
            if(!exists) { error404(res); }
            else {
                res.writeHead(200, {'Content-Type': 'text/css'});
                var fileStream = fs.createReadStream('./client/css/' + file);
                fileStream.pipe(res);
                return;
            }
        });
    }
    else { error404(res); }
}).listen(8080);

Now I have three questions :

  • 1) Would this piece of code create a secure server and reliable ?
  • 2) What could be improved ?
  • 3) What are the advantages of using Express.js compared to this combined with "Connect" ?

Thank you a lot in advance !

(Info : I count on using this code later combined with "Handlebars", "Socket.io" and "Mongoose / MongoDB".)

You should definitely just use express.

Otherwise, you'll waste a lot of your time reinventing the wheel.