Last active
August 29, 2015 14:07
-
-
Save adohe-zz/939fcb8a86f441afe7a6 to your computer and use it in GitHub Desktop.
request timeout handler
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'), | |
parse = require('url').parse; | |
function requestUrl(url, callback) { | |
var urlObj = parse(url), | |
path = urlObj.pathname + (urlObj.search || ''), | |
options = { | |
hostname: urlObj.hostname, | |
path: path, | |
port: urlObj.port || 80, | |
method: 'GET' | |
}, | |
req = null, | |
response_timeout = setTimeout(function() { | |
response_timeout = null; | |
req.abort(); | |
callback("Response timeout"); | |
}, 5000); | |
req = http.request(options, function (res) { | |
res.setEncoding('utf-8'); | |
var chunks = [], | |
length = 0; | |
res.on('data', function(chunk) { | |
chunks.push(chunk); | |
length += chunk.length; | |
}).on('end', function () { | |
var data = new Buffer(length), | |
pos = 0, | |
l = chunks.length; | |
for(var i = 0; i < l; i++) { | |
chunks[i].copy(data, pos); | |
pos += chunks[i].length; | |
} | |
res.body = data; | |
callback(null, res); | |
}).on('error', function(err) { | |
callback(err, res); | |
}); | |
}).on('error', function(err) { | |
if(response_timeout) { | |
clearTimeout(response_timeout); | |
callback(err); | |
} | |
}); | |
req.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment