javascript - google URL shortener, wait for data to be fully received - NodeJS -
i trying use google's url shortener api. using code shorten using node js:
function _shorten (url, callback) { if (!url) { console.error('please specify 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); // <--- here 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(); }
however, when try run basic url, following error:
undefined:1 { ^ syntaxerror: unexpected end of input @ object.parse (native) @ incomingmessage.<anonymous> (/users/path/node_modules/goo.gl/lib/googl.js:45:26) @ incomingmessage.eventemitter.emit (events.js:95:17) @ incomingmessage.<anonymous> (_stream_readable.js:746:14) @ incomingmessage.eventemitter.emit (events.js:92:17) @ emitreadable_ (_stream_readable.js:408:10) @ emitreadable (_stream_readable.js:404:5) @ readableaddchunk (_stream_readable.js:165:9) @ incomingmessage.readable.push (_stream_readable.js:127:10) @ httpparser.parseronbody [as onbody] (http.js:142:22)
i believe because trying parse data receive before received completely. when remove d = json.parse(d); callback gets called several times , following result:
{ " k n d " : " u r l s hortener#url", "id": "http://goo.gl/test", "longurl": "http://test.com" }
how can fix this? should interested in 'id' field?:
if d contains 'id' d = json.parse(d); if (callback) { callback(d); } else { console.log(d.id || d.error); }
thanks
you need accumulate data until finishes , json.parse()
. keep augmenting data within .on('data',...)
event handler , need transfer json.parse()
, callback
existence check in .on('end',...)
event handler.
from nodejs documentation on http.clientrequest:
however, if add 'response' event handler, must consume data response object, either calling response.read() whenever there 'readable' event, or adding 'data' handler, or calling .resume() method. until data consumed, 'end' event not fire. also, until data read consume memory can lead 'process out of memory' error.
Comments
Post a Comment