Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple request
var http = require('http')
, parse = require('url').parse
, StringDecoder = require('string_decoder').StringDecoder;
var LIMIT = 10 * 1024;
var request = function(url, body, func) {
if (typeof url !== 'object') {
url = parse(url);
}
if (!func) {
func = body;
body = undefined;
}
var opt = {
host: url.hostname,
port: url.port || 80,
path: url.pathname + (url.search || '')
//agent: false
};
if (body) {
opt.headers = {
'Content-Length': Buffer.byteLength(body)
};
opt.method = 'POST';
} else {
opt.method = 'GET';
}
var req = http.request(opt);
req.on('response', function(res) {
var decoder = new StringDecoder('utf8')
, total = 0
, body = ''
, done = false;
var end = function() {
if (done) return;
done = true;
res.body = body;
func(null, res);
};
res.on('data', function(data) {
total += data.length;
body += decoder.write(data);
if (total > LIMIT) {
this.destroy();
end();
}
}).on('error', function(err) {
this.destroy();
func(err);
});
// an agent socket's `end` sometimes
// wont be emitted on the response
res.on('end', end);
res.socket.on('end', end);
});
req.end(body);
};
request('http://google.com/?q=testing', function(err, res) {
console.log(err, res && res.body);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.