HTTP node静态资源请求加载demo

MIME type的缩写为(Multipurpose Internet Mail Extensions)代表互联网媒体类型(Internet media type),MIME使用一个简单的字符串组成,最初是为了标识邮件Email附件的类型,在html文件中可以使用content-type属性表示,描述了文件类型的互联网标准。

自己总结的小demo:贴出server部分的代码,每一行代码都有注释,有不对的地方,希望大家多多指正哈

var http=require("http");
var url=require("url");
var fs=require("fs");
var path=require("path");
var MIME_TYPE = {
    "css": "text/css",
    "gif": "image/gif",
    "html": "text/html",
    "ico": "image/x-icon",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "js": "text/javascript",
    "json": "application/json",
    "pdf": "application/pdf",
    "png": "image/png",
    "svg": "image/svg+xml",
    "swf": "application/x-shockwave-flash",
    "tiff": "image/tiff",
    "txt": "text/plain",
    "wav": "audio/x-wav",
    "wma": "audio/x-ms-wma",
    "wmv": "video/x-ms-wmv",
    "xml": "text/xml"
};
function start(router,handle){
    function onRequest(request,response){
        var pathname=url.parse(request.url).pathname;
         var filePath;
        request.setEncoding("utf8");
        if(typeof handle[pathname] === 'function'){//如果有对应的处理方法
        router(handle,pathname,response);
        }else{         //如果请求的是静态数据。如果没有,判断是否是静态数据
            filePath= "/public" + url.parse(request.url).pathname;
            fs.exists(__dirname +filePath,function(err){
            if(!err){
                response.writeHead(404,{'content-type':'text/plain' });
                response.write('The Resourse '+pathname+' was Not Found!');
                response.end();
            }else{//文件存在
                //获取文件的扩展名称,如果没有返回" "
                var ext = path.extname(filePath);
                //如果扩展名称为空,设置扩展名称为unknown
                ext = ext?ext.slice(1) : 'unknown';
                //根据请求文件的扩展名称,设置请求的类型contentType
                var contentType = MIME_TYPE[ext] || "text/html";
                console.log(filePath);
                //因为有图片,默认读取文件是以utf8读取的,获取不到图片,需要读文件是和返回文件时都用binary编码,不然图片不能正常显示
                fs.readFile(__dirname +filePath,"binary",function(err,data){
                    if(err){
                        response.end("<h1>500</h1>服务器内部错误!");
                    }else{//返回不同的页面
                        response.writeHead(200,{'content-type':contentType});
                        response.end(data.toString(),"binary");
                    }
                });//fs.readfile
        }
        });
    }
    
    }
    http.createServer(onRequest).listen(8888);
    console.log("Server runing at port:8888.");
    }
exports.start=start;
path.exname(filePath),返回filePath路径文件的扩展名,如果filePath以.为结尾,将返回.,如果无扩展名,将返回空

  

原文地址:https://www.cnblogs.com/xiaofenguo/p/5984551.html