1 var http = require('http'); 2 3 var fs = require('fs'); 4 5 var path = require('path'); 6 7 var mime = require('mime'); 8 9 //用来缓存文件内容 10 var cache = {}; 11 12 13 14 function send404(res){ 15 res.writeHead(404, {'Content-Type': 'text/plain'}); 16 res.write('Error 404: resource not found'); 17 res.end(); 18 } 19 20 function sendFile(res, filePath, fileContents){ 21 res.writeHead(200, { 22 'Content-Type': mime.lookup(path.basename(filePath)) 23 }); 24 res.end(fileContents); 25 } 26 27 /*访问内存(RAM)要比访问文件系统快得多,所以Node程序通常会把常用的数据缓存到内存里。 28 我们的聊天程序就要把静态文件缓存到内存中,只有第一次访问的时候才会从文件系统中读取。*/ 29 30 function serveStatic(res, cache, absPath){ 31 if(cache[absPath]){ 32 sendFile(res, absPath, cache[absPath]); 33 }else{ 34 fs.exists(absPath, function(exists){ 35 if(exists){ 36 fs.readFile(absPath, function(err, data){ 37 if(err){ 38 send404(res); 39 }else{ 40 cache[absPath] = data; 41 sendFile(res, absPath, data); 42 } 43 }); 44 }else{ 45 send404(res); 46 } 47 48 }); 49 } 50 } 51 52 var server = http.createServer(function(req, res){ 53 var filePath = false; 54 55 if(req.url == '/'){ 56 filePath = 'public/index.html'; 57 }else{ 58 filePath = 'public'+ req.url; 59 } 60 61 var absPath = './'+ filePath; 62 fs.readFile(absPath, function(err, data){ 63 if(err){ 64 send404(res); 65 }else{ 66 //cache[absPath] = data; 67 sendFile(res, absPath, data); 68 } 69 }); 70 //serveStatic(res, cache, absPath); 71 }); 72 server.listen(2000, function(){ 73 console.log('server listen in 2000'); 74 }); 75 76 77 var chatServer = require('./lib/chat_server'); 78 chatServer.listen(server);
浙公网安备 33010602011771号