码迷,mamicode.com
首页 > Web开发 > 详细

NodeJS http 模块

时间:2015-11-09 10:30:36      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

#4 NodeJS http 模块


工作目录

技术分享

server.js

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‘);

})

index.html

技术分享

按住Shift键不放,空白处右键,选择Open command windows here

技术分享

执行下图命令

技术分享

看到下图收摊

技术分享


NodeJS http 模块

标签:

原文地址:http://www.cnblogs.com/kkun/p/4949014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!