2013-08-23 36 views
2

我是Node.js的新手。我想知道什么是这两个码片的区别:有或没​​有结束事件请求,有什么区别?

var http = require("http"); 

http.createServer(function(request,response) { 
    request.addListener("end", function(){ 
     console.log(request); 
    }); 

}).listen(8888); 

var http = require("http"); 

http.createServer(function(request,response) { 

    console.log(request); 

}).listen(8888); 

换句话说,由于end事件被触发每次服务器接收完数据,时间又何必使用它?一个新手问题。

+0

我猜是因为套接字 –

回答

2

我不是NodeJS专家,但以下流程从文档中逻辑流动。

考虑上传大文件的请求。当请求第一次到达服务器时,调用您传递到createServer的回调; request对象(继承自ReadableStream)上的end事件在请求完全发送时触发。那将是相当不同的时代。

1

如果您将任何数据发送到此服务器意味着您必须使用该request.listener来获取该数据。

var http = require("http"); 

http.createServer(function(req,response) { 

req.on('data', function (chunk) { 

     body += chunk; 

    }); 

    req.on('end', function() { 

     console.log('POSTed: ' + querystring.parse(body).urDataName); 

     var data=querystring.parse(body).urData;//here u can get the incoming data 

    }); 

}).listen(8888); 
2

你的第二个代码可能不会做你期望的,因为console.log(...)将在每次有传入请求时运行。但是没有办法知道请求是否已经完成(即完全发送到服务器)。
每次关闭连接并完成请求(即每次有人请求数据时),您的第一个代码都会运行console.log(...)。然后您可以使用传输的数据。所以你可能想要使用的(并且通常在处理请求时使用)是第一个代码。