title: In node.js if no response is received from an http request, how do you know?
body: <p>OK so in the below example I request something from a server. If a response comes back I parse the JSON and add the data to my mongodb. </p>
  
  <p>However if NO response comes back, then no event fires evidently. How would I add a timeout to this so that if no response is received, then I can cancel the request without any errors being thrown, and call a function? (I'm going to make it call a function that emails me.)</p>
  
  <p>Thanks!</p>
  
  <pre><code>var req = https.request(options, function(res) {
          res.on('data', function(d) {
              if(d) buffer += d;
          });
  
          res.on('end', function(){
              var validResponse = true;
              var object;
              try {
                  object = JSON.parse(buffer);
              } catch (err) {
                  console.log('response: '+ buffer);
                  console.log('error in response: ' + err);
                  validResponse = false;
              }
              if(validResponse) {
                  db.stuff.update(
                      {stuff: "MyStuff"},
                      {stuff: "MyStuff", foo: object.bar},
                      {upsert: true},
                      function() {
                          var time2 = new Date();
                          console.log('db successfully updated db at '+time2.toTimeString());
                      }
                  );
              }
          });
      });
  </code></pre>