user3998223
user3998223

Reputation:

How does node.js http.get() "on(end,callback())" event works?

My question is: How does the "http.get()", on.("end",callback) event work?

What is the hierarchy of the code execution?

I'm asking because I have this code

var http = require("http")
var str = ""

http.get(process.argv[2],function(res){
    res.setEncoding("utf8")
    res.on("data",function(data){
        str+= data

    })

    res.on("end",function(){
        console.log(str.length)
        console.log(str)


    })

})

is the on.end part would print me the str.length every time its called?

Upvotes: 1

Views: 3009

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 356

To start with,

  • function(res) is called when the connection is established.
  • on('data') is called when there's a chunk of data (this almost certainly will be more than once)
  • on('end') is called when the connection closes.
  • on('error') is called when there is some sort of error.

This code means that till the data is incoming (in chunks), the response will be appended every time it is received from data to str and when the receiving has ended it will console str.length and str.

You can read this for better understanding: colmsjo.com/130721_Streams_in_NodeJS

Upvotes: 5

Related Questions