NodeJS http 模塊

#4 NodeJS http 模塊html


工做目錄windows

Image

server.jsui

var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
function send404(response){
     response.writeHead(404,{
          'Content-Type':'text/plain'
     });
     response.write('Error 404 : resource not found.');
     response.end();
}
function sendFile(request,response,filePath){
     fs.exists(filePath,function(exists){
          if(!exists){
               return send404(response);
          }
          fs.readFile(filePath,function(err,data){
               if(err) send404(response);
               response.writeHead(200,     {
                    'content-type':mime.lookup(path.basename(filePath))
               });
               response.end(data);
          })
     })
}
var server = http.createServer(function(request,response){
     var filePath = '';
     if(request.url == '/'){
          filePath = 'public/index.html';
     }else{
          filePath = './public' + request.url;
     }
     sendFile(request,response,filePath);
});
server.listen(3000,function(){
     console.log('Server listening on 3000');url

})server

index.htmlhtm

Image(13)

按住Shift鍵不放,空白處右鍵,選擇Open command windows hereblog

Image(14)

執行下圖命令it

Image(15)

看到下圖收攤io

Image(16)

相關文章
相關標籤/搜索