title: Getting the request.https response into a variable
body: <p>Today I am doing this request to Linode API.</p>
  
  <pre><code>var options = {
      hostname: 'api.linode.com',
      path: '',
      port: 443,
      method: 'GET'
  }
  
  var req = https.request(options, function(response) {
      response.setEncoding('utf8');
      response.on('data', function(d) {
          body = JSON.parse(d.toString());
      });
  
      response.on('end', function() {
          console.log(body);
      });
  }).end();
  </code></pre>
  
  <p>The output is working as expected on this example.</p>
  
  <p>However, I need to put the response into a variable, and not log it to console.</p>
  
  <pre><code>var body = '';
  var req = https.request(options, function(response) {
      response.setEncoding('utf8');
      response.on('data', function(d) {
          body = JSON.parse(d.toString());
      });
  }).end();
  console.log(body);
  return body;
  </code></pre>
  
  <p>Running the above code, the answer is always empty, since looks like the <code>console.log()</code> function or <code>return</code> clause are not waiting for end of the request.</p>
  
  <p>I resolved the problem using the <code>setTimeout( function() { console.log(body); }, 2000 )</code> function, but to be honest can't see it as an effective solution, since the timeout will be different on each request.</p>
  
  <p>Other solution I tried was <code>while (!req.finished) {} console.log(body);</code>, but it is not working as expected too.</p>
  
  <p>Finally, I tried to add this:</p>
  
  <pre><code>response.on('end', function() {
      return body;
  });
  </code></pre>
  
  <p>But no success as well :(</p>
  
  <p>That said, do you have any suggestions to make this function wait for request timeout before return the value of the <code>body</code> variable?</p>