Last active
August 29, 2015 13:57
-
-
Save pasupulaphani/9630789 to your computer and use it in GitHub Desktop.
Handling requests and parsing responses via http.get or http.response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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