使用Node.js轮询REST服务

我正在开发一个服务,每分钟轮询Foursquare进行特定的检查,并在NoSQL数据库中保存/更新结果。 用setInterval封装一个http.request,然后使用数据事件发射器聚合分块的响应是最好的方法吗? 我计划使用最终发射器parsingJSON,并在请求完成时将其推入NoSQL DB。 思考?

可能有更好的方法,但我最终只使用事件发射器来处理REST响应,如下所示:

var fourSquareGet = { host: 'api.foursquare.com', port: 443, path: '/v2/venues/search?ll=33.88,-119.19&query=burger*', method: 'GET' }; setInterval(function () { var reqGet = https.request(fourSquareGet, function (res) { var content; res.on('data', function (chunk) { content += chunk; }); res.on('end', function () { // remove 'undefined that appears before JSON for some reason content = JSON.parse(content.substring(9, content.length)); db.checkins.save(content.response.venues, function (err, saved) { if (err || !saved) throw err; }); console.info("\nSaved from Foursquare\n"); }); }); reqGet.end(); reqGet.on('error', function (e) { console.error(e); }); }, 25000); 

不过,我不知道为什么我从我从Foursquare收到的JSONparsing出“undefined”。

我已经修复了@occasl的答案,并且为了清晰起见而进行了更新:

 var https = require('https'); setInterval(function () { var rest_options = { host: 'api.example.com', port: 443, path: '/endpoint', method: 'GET' }; var request = https.request(rest_options, function(response) { var content = ""; // Handle data chunks response.on('data', function(chunk) { content += chunk; }); // Once we're done streaming the response, parse it as json. response.on('end', function() { var data = JSON.parse(content); //TODO: Do something with `data`. }); }); // Report errors request.on('error', function(error) { console.log("Error while calling endpoint.", error); }); request.end(); }, 5000); 

当我遇到类似的问题时,我采用了类似的技术,结果很好。 这是我从中得到的想法 。 希望这会有所帮助。