node - a static resource files management

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

http.createServer(function(req,res){
    // get the user's path
    var pathname = url.parse(req.url).pathname;
    // default home page
    if(pathname == "/"){
        pathname = "index.html";
    }
    // expand name
    var extname = path.extname(pathname);

    // really read the file
    fs.readFile("./static/" + pathname,function(err,data){
        if(err){
            // If this file does not exist, it should return with 404
            fs.readFile("./static/404.html",function(err,data){
                res.writeHead(404,{"Content-type":"text/html;charset=UTF8"});
                res.end(data);
            });
            return;
        };
      
        var mime = getMime(extname);
        res.writeHead(200,{"Content-type":mime});
        res.end(data);
    });

}).listen(3000,"127.0.0.1");

function getMime(extname){
    switch(extname){
        case ".html" :
            return "text/html";
            break;
        case ".jpg" :
            return "image/jepg";
            break;
        case ".png" :
            return "image/png";
            break;
        case ".css":
            return "text/css";
            break;
        case ".js":
            return "application/javascript";
            break;
        case ".json":
            return "application/json";
            break;  
    }
}

Guess you like

Origin www.cnblogs.com/500m/p/10977484.html