Skip to content

Instantly share code, notes, and snippets.

@tobsn
Forked from chjj/simple_request.js
Created May 4, 2012 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobsn/2597629 to your computer and use it in GitHub Desktop.
Save tobsn/2597629 to your computer and use it in GitHub Desktop.
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