1 /**2 * Node Entry integrated case (i): Easy routing3 * @Author: by Ghost4 * @Date: 2016/07/115 * @Description:6 * 1, introduce the following modules7 * HTTP Module: Create server, process request and corresponding8 * URL module: Resolve URL request address9 * FS module: Read FileTen * Path module: Process file path, get file suffix name, path optimization One * A * 2. Create a server using the Http.createserver () method - * 3. Use the Url.parse () method to parse the browser request path - * 4, use the Fs.readfile () method to read the corresponding static file the * 5, use the Path.extname () method to get the file suffix name - * 6, Set MIME type, achieve file compatibility - * */ - + //Introducing Modules - varHTTP = require (' http '); + varurl = require (' URL ')); A varFS = require (' FS '); at varPath = require (' path '); - - //creating a server, listening on port 3000 - varServer = Http.createserver (function(req, res) { - //request to block/favicon.ico - if(Req.url = = = '/favicon.ico ')) in { - return ; to }; + - //Parse Request Path the varpathname =Url.parse (req.url). Pathname; * $ //Default HomePanax Notoginseng if(Pathname.indexof ('. ') = = =-1) - { thepathname = "/index.html" + }; A the //get file suffix name + varExtname =path.extname (pathname); - $ //Read File $Fs.readfile ('./static/' + pathname,function(err,data) { - //If an error indicates that the request path is incorrect, the 404 is displayed - if(err) { theFs.readfile ("./static/404.html",function(err,data) { -Res.writehead (404,{"Content-type": "Text/html;charset=utf-8"});Wuyi res.end (data); the }); - return; Wu }; - About //reading Data $ //End Response -Getmime (Extname,function(MIME) { -Res.writehead (200,{"Content-type": MIME}); - res.end (data); A }); + }); the }); - $ //Setting the Listening port theServer.listen (3000, ' 127.0.0.1 ',function () { theConsole.log ("Server is started listen Port 3000"); the }); the - //getmime () in functiongetmime (extname,callback) the { theFs.readfile ('./static/mime.json ',function(err,data) { About if(ERR) the { the ThrowError ("Mime.json File not Found"); the return; + }; - varMimejson =json.parse (data); the varMIME = Mimejson[extname] | | "Text/plain";Bayi //Execute callback function to end async problem the callback (MIME); the }); -}
Node. JS Series (instance): Native node. js for static resource management