kikit
6/22/2016 - 7:29 AM

Serving static files

Serving static files

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

http.createServer(function(request, response){
    var lookup = path.basename(decodeURI(request.url)) || 'index.html';
    var f = 'content/' + lookup;
    fs.exists(f, function(exists){
        console.log(exists ? lookup + " is there." : lookup + " doesn't exists.");
    });
}).listen(8080);
var http = require("http");
var path = require("path");
var fs = require("fs");

var mimeType = {
    '.js' : 'text/javascript',
    '.html' : 'text/html',
    '.css' : 'text/css'
};

http.createServer(function(request, response){
    var lookup = path.basename(decodeURI(request.url)) || 'index.html';
    var f = 'content/' + lookup;
    fs.exists(f, function(exists){
        if(exists){
            fs.readFile(f, function(err, data){
                if(err){
                    response.writeHead(500);
                    response.end("Server Error!");
                    return;
                }
                var headers = {'content-type' : mimeType[path.extname(lookup)] };
                response.writeHead(200, headers);
                response.end(data);
            });
            return;
        }
        response.writeHead(404);
        response.end("Page not Found!");
    });
}).listen(8080);