简体   繁体   中英

Node http.request () : the relationship with var ClientRequest and callbackFn

I am a newbie to Node.js .

And I am trying to further explore Node.js API .

I referred and wrote a crawler and the code works.

I have successfully post the comment to the website.

But I am confused with the execution order with return class - clientRequest and

callbackFn .

var req = http.request(urlRequest,function(res){
console.log("Status: "+res.statusCode);
console.log("headers: "+JSON.stringify(res.headers));

res.on("data",function(chunk){
    console.log(Buffer.isBuffer(chunk));
    console.log(typeof chunk);
});

res.on("end",function(){
    console.log("comment success!");
});
});

req.on('error',function(e) {
console.log("Error :"+e.message);
});

req.write(postData);

req.end();

My original understanding for the steps are as below :

1) http.request(urlRequest

2) function(res)

3) And last return the clientRequest-class var req

But from the code , it seems my understanding is wrong .

It should be clientRequest-class-object var req 'write' the comments and

take it 'end' and then trigger the callbackFn function(res) .

Pls sharing your opinions and tell me more about this API.

Thanks & Best regard.

It seems the asynchronous nature of http.request may be causing your confusion.

Basically, the request call will be made - this takes some time. Meanwhile JS will move onto req.write() etc.

You should look into EventEmitters, you are already using them technically inside of the request callback (eg. res.on("data",function(chunk) ).

Perhaps a better move would be to put the calls outside of the request into another callback function which you then call inside of the request. This will cause it to be called at the end of the request - as signaled by the "end" emitter:

res.on("end",function(){
    console.log("comment success!");
    requestWrite();
});

function requestWrite(){
    req.write(postData);
    req.end();
}

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