The abbreviation for MIME type is (Multipurpose Internet Mail Extensions) represents the Internet media type (Internet multimedia type), MIME uses a simple string composition, It was originally designed to identify the type of email attachment, which can be represented in an HTML file using the Content-type attribute, which describes the Internet standards for file types.
My summary of the small demo: The server part of the code, each line of code has comments, there is no place, I hope that we have a lot of AH
varHttp=require ("http");varUrl=require ("URL");varFs=require ("FS");varPath=require ("Path");varMime_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) {varPathname=Url.parse (request.url). Pathname; varFilePath; Request.setencoding ("UTF8"); if(typeofHandle[pathname] = = ='function'){//if there is a corresponding processing methodrouter (handle,pathname,response); }Else{//if the request is static data. If not, determine if the data is staticFilepath="/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{//File exists//gets the extension name of the file, if no return "" varext =Path.extname (FilePath); //If the extension name is empty, set the extension name to unknownext = Ext?ext.slice (1) :'Unknown'; //sets the type of the request, based on the extension name of the requested file ContentType varContentType = Mime_type[ext] | |"text/html"; Console.log (FilePath); //because there is a picture, the default read file is read in UTF8, not get the picture, need to read the file is and return the file is encoded with binary, otherwise the picture will not display properlyFs.readfile (__dirname +filepath,"binary", Function (err,data) {if(Err) {Response.End (""); }Else{//return to different pagesResponse.writehead ( $,{'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), returns the extension of the FilePath path file, if FilePath ends with., returns null if no extension is available.
HTTP node static resource request loading demo