title: google URL shortener, wait for data to be fully received - NodeJS
body: <p>I am trying to use Google's URL shortener API.
  I am using this code to shorten it using node JS:</p>
  
  <pre><code>function _shorten (url, callback) {
      if (!url) { 
          console.error('Please specify a valid url.');
          return; 
      }
  
      if (typeof _url.parse(url).protocol === 'undefined') {
          url = 'http://' + url;
      }
  
      if (!callback) { callback = false; }
  
      var key = _getKey(),
          options = {
              host: 'www.googleapis.com',
              port: 443,
              path: '/urlshortener/v1/url' + (key ? '?' + _querystring.stringify({'key': key}) : ''),
              method: 'POST',
              headers: {
                  'content-type': 'application/json'
              }
          };
  
      var req = _https.request(options, function(res) {
          res.setEncoding('utf8');
          res.on('data', function (d) {
              d = JSON.parse(d); // &lt;--- here is the problem
              if (callback) {
                  callback(d);
              } else {
                  console.log(d.id || d.error);
              }
          });
      });
  
      req.on('error', function(e) { console.error(e); });
  
      req.write(JSON.stringify({'longUrl': url}));
  
      req.end();
  }
  </code></pre>
  
  <p>However, when I try to run it with a basic URL, I get the following error:</p>
  
  <pre><code>undefined:1
  {
   ^
  SyntaxError: Unexpected end of input
      at Object.parse (native)
      at IncomingMessage.&lt;anonymous&gt; (/Users/PATH/node_modules/goo.gl/lib/googl.js:45:26)
      at IncomingMessage.EventEmitter.emit (events.js:95:17)
      at IncomingMessage.&lt;anonymous&gt; (_stream_readable.js:746:14)
      at IncomingMessage.EventEmitter.emit (events.js:92:17)
      at emitReadable_ (_stream_readable.js:408:10)
      at emitReadable (_stream_readable.js:404:5)
      at readableAddChunk (_stream_readable.js:165:9)
      at IncomingMessage.Readable.push (_stream_readable.js:127:10)
      at HTTPParser.parserOnBody [as onBody] (http.js:142:22)
  </code></pre>
  
  <p>I believe this is because I am trying to parse the data I receive before I received it completely. When I remove  d = JSON.parse(d); my callback gets called several times and I get the following result:</p>
  
  <pre><code>{
  
  
  
  "
  k
  i
  n
  d
  "
  :
  
  "
  u
  r
  l
  s
  hortener#url",
   "id": "http://goo.gl/test",
   "longUrl": "http://test.com"
  }
  </code></pre>
  
  <p>How can I fix this? Should I do something like this as I am only interested in the 'id' field?:</p>
  
  <pre><code>    if d contains 'id' then 
       d = JSON.parse(d);
              if (callback) {
                  callback(d);
              } else {
                  console.log(d.id || d.error);
              }
  </code></pre>
  
  <p>thanks</p>