title: Nodejs Listening to response stream on data event from http.get()
body: <p>I am studying Node.js. For this I am using useful nodeschool.io workshops. I am reading the learnyounode workshop now.</p>
  
  <p>In the http client and http collect parts I have a problem. Despite I have read them and the api docs on node.js. Challenge in the first one was; "Write the String contents of each "data" event from the response to a new line on the console (stdout).". It says in the https collect part that "Collect all data from the server (not just the first "data" event)..." And refer the first one as it does not collects all data. Isn't a </p>
  
  <pre><code>var allData = "";
  response.setEncoding('utf8');
  response.on('data', function(data){
      allData = concat(allData, data);
  }
  </code></pre>
  
  <p>capable of collecting all data from  the response.</p>
  
  <p>As far as I have understood async nature so far, following first callback will be called when the async <code>http.get()</code> is completed. Or I am wrong the <code>http.get()</code> is not async.</p>
  
  <pre><code>var http = require('http');
  var urlString = process.argv[2];
  http.get(urlString, function callback (response) {
      response.setEncoding('utf8');
      response.on('data', console.log);
      response.on('error', console.error);
  })
  </code></pre>
  
  <p>What happens while this code is executing. Does callback waits to <code>http.get()</code> to finish and supply a <code>response</code>, so <code>http.get()</code> is async? If so when the events are fired that <code>response.on(..)</code> lines are listening for, after its creation. </p>
  
  <p>Isn't that listening a continuous process that is performed while <code>response</code> is being created, in that case <code>callback</code> should not wait for the <code>http.get()</code> to complete execution so that event listener be available for events fired by <code>response</code> object?</p>
  
  <p>An explanation can be that; what http.get() does to create a response object to server write on it and finish. So it finished its job by creating response object and from now on possibly server will start to write to this response stream, and callback has already taken on, on to listening the response stream for 'data' events fired when server writes any bit of data to it. That would be logically possible.</p>