Skip to content

Instantly share code, notes, and snippets.

@tobsn
Forked from chjj/simple_request.js
Created May 20, 2011 01:10
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/982144 to your computer and use it in GitHub Desktop.
Save tobsn/982144 to your computer and use it in GitHub Desktop.
simple request
var parse = require('url').parse,
http = require('http'),
StringDecoder = require('string_decoder').StringDecoder;
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
};
if (body) {
opt.headers = {
'Content-Type': 'application/octet-stream; charset=utf-8',
'Content-Length': Buffer.byteLength(body)
};
opt.method = 'POST';
} else {
opt.method = 'GET';
}
var req = http.request(opt, function(res) {
var decoder = new StringDecoder('utf-8'),
total = 0, body = '';
res.on('data', function(data) {
if (total += data.length > 10240) {
this.emit('error');
return;
}
body += decoder.write(data);
}).on('error', function(err) {
func(err);
this.destroy();
}).on('end', function() {
res.body = body;
func(null, res);
});
});
req.end(body);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment