简体   繁体   中英

With or without the end event for request, what's the difference?

I am new to Node.js. I want to know what's the difference between these two pieces of codes:

var http = require("http");

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

}).listen(8888);

and

var http = require("http");

http.createServer(function(request,response) {

    console.log(request);

}).listen(8888);

In other words, since the end event is triggered every time the server finishes receiving data, why bother using it? A newbie question.

I'm not a NodeJS expert, but the following flows logically from the documentation.

Consider a request that uploads a large file. The callback you pass into createServer is called when the request first arrives at the server; the end event on the request object (inherited from ReadableStream ) fires when the request has been completely sent. Those would be rather different times.

Your second code probably won't do what you would expect, because the console.log(...) will be run every time there is an incoming request. But there is no way of telling if the request was already completed (ie fully sent to the server).
Your first code runs the console.log(...) every time a connection is closed and the request finished (ie every time someone requested data). You can then use the transmitted data. So what you probably want to use (and normally do use when processing requests) is the first code.

If you are sending any data to this server means you have to use that request.listener to get that data.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM