Created
March 19, 2016 12:40
-
-
Save koreapyj/0e5a6bfabb2947b2559c to your computer and use it in GitHub Desktop.
[Node.js] simpleRequest
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 simpleRequest = function(url,callback,method,headers,data) { | |
var parser = require('url'); | |
if(!(url = parser.parse(url))) { | |
throw new UserException("simpleRequest: Invalid URL"); | |
return false; | |
} | |
var protocol = url.protocol.replace(/:$/, ''); | |
switch(protocol) { | |
case 'http': | |
if(!url.port) | |
url.port=80; | |
break; | |
case 'https': | |
if(!url.port) | |
url.port=443; | |
break; | |
default: | |
throw new UserException("simpleRequest: Unknown protocol \""+protocol+"\""); | |
return false; | |
} | |
var http = require(protocol); | |
var details = {host:url.hostname,port:url.port,path:url.path,method:method?method:"GET",auth:url.auth,headers:headers}; | |
if(headers) { | |
details.headers = headers; | |
} | |
var req = http.request(details,function(res) { | |
var data = ''; | |
var utf8 = true; | |
var encoding = null | |
var match= null; | |
var iconv = require('iconv').Iconv; | |
var encoder = null; | |
if(res.headers['content-type'] && (match = res.headers['content-type'].match(/charset=(.*)$/))) { | |
if(match[1].toLowerCase()!='utf-8') { | |
utf8 = false; | |
encoding = match[1]; | |
encoder = new iconv(encoding, 'UTF-8'); | |
} | |
} | |
res.on('data', function(chunk) { | |
data += utf8?chunk:encoder.convert(chunk).toString('UTF-8'); | |
}); | |
if(callback) | |
res.on('end', function() { | |
callback({responseXML:"",responseText:data,responseHeaders:res.headers,status:res.statusCode}); | |
}); | |
}); | |
if(data) { | |
req.write(data); | |
} | |
req.end(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment