1 var http = require("http"); 2 var url = require("url"); 3 var fs = require("fs"); 4 var path = require("path"); 5 6 http.createServer(function(req, res) { 7 //得到用户的路径 8 var pathname = url.parse(req.url).pathname; 9 //默认首页 10 if (pathname == "/") { 11 pathname = "index.html"; 12 } 13 //拓展名 14 var extname = path.extname(pathname); 15 16 //真的读取这个文件 17 fs.readFile("./" + pathname, function(err, data) { 18 if (err) { 19 //如果此文件不存在,就应该用404返回 20 fs.readFile("./static/404.html", function(err, data) { 21 res.writeHead(404, { 22 "Content-type": "text/html;charset=UTF8" 23 }); 24 res.end(data); 25 }); 26 return; 27 }; 28 //MIME类型,就是 29 //网页文件: text/html 30 //jpg文件 : image/jpg 31 var mime = getMime(extname); 32 res.writeHead(200, { 33 "Content-type": mime 34 }); 35 res.end(data); 36 }); 37 38 }).listen(3000, "127.0.0.1"); 39 40 function getMime(extname) { 41 switch (extname) { 42 case ".html": 43 return "text/html"; 44 break; 45 case ".jpg": 46 return "image/jpg"; 47 break; 48 case ".css": 49 return "text/css"; 50 break; 51 } 52 }