简体   繁体   中英

Node request module Http.IncomingMessage not emitting events

According to this link: request - Node

The callback argument gets 3 arguments:

An error when applicable (usually from http.ClientRequest object) An http.IncomingMessage object The third is the response body (String or Buffer, or JSON object if the json option is supplied)

Code:

var r = require("request");

var options= {
    url: "http://www.example.com/" 
};

var callback = function (err, res, body) {
    if (!err && res.statusCode == 200) {
        res.on("data", function(chunk) {
            console.log("DATA : "+chunk);
        });
        res.on("finish", function() {
            console.log("FINISHED");
        });
        console.log(body);
    }
};

r(options, callback);

But in the above code, only the console.log(body) works, the event emitters don't.

Also, if the callback would be invoked only when the whole response is body is available, then what's the point of making the second argument as http.IncomingMessage (Readable Stream) when I can't stream it.

When you pass a callback like that, request buffers the entire response for you and that is what is available in body . Because of this, that means you won't see data and such events on res , because they've already been taken care of by request .

It looks like you're mixing two different ways to use the 'request' module. Depending on preference you can use either the callback approach or the streaming approach.

The callback approach involves passing a function as well as the options and when all the data is received it will call the callback function.

The streaming approach allows you to attach listeners to the events such as 'response'. I'm guessing you've mixed this code in from an example from receiving http requests and sending a response with a node server as I can't see any reference to 'data' and 'finish' events in the docs for the request module.

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