Skip to content

Instantly share code, notes, and snippets.

@pasupulaphani
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pasupulaphani/9630789 to your computer and use it in GitHub Desktop.
Save pasupulaphani/9630789 to your computer and use it in GitHub Desktop.
Handling requests and parsing responses via http.get or http.response
var Fiber = require('fibers')
var getResp = function (url, callback) {
var fn = Fiber(function () {
var resp = handleRequest(url);
if (resp.statusCode != 200) {
//handle success response
} else {
//handle other responses here
}
callback && callback();
});
try {
fn.run();
} catch(e) {
console.log('caught error!', e);
console.log(e.stack);
}
}
var http = require('http');
var Fiber = require('fibers')
module.exports = function handleRequest(url) {
var fiber = Fiber.current;
http.get(url, function(res) {
if (res.statusCode !== 200) {
console.log(url + "returned : ", res.statusCode);
var result = {statusCode: res.statusCode};
fiber.run(result);
} else {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var result = JSON.parse(body);
result.statusCode = res.statusCode
fiber.run(result);
});
}
}).on('error', function(e) {
console.log("error: ", e);
var result = {statusCode: res.statusCode};
fiber.run(result);
});
var resp = Fiber.yield();
return resp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment