This repository has been archived by the owner on May 19, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
fetch.js
70 lines (64 loc) · 2 KB
/
fetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
var http = require('http');
var https = require('https');
var url = require('url');
var util = require('util');
function get(inputUrl,options,config,callback) {
var u = url.parse(inputUrl);
var doRequest = (u.protocol && u.protocol.startsWith('https')) ? https.get : http.get;
options.hostname = u.host;
options.port = u.port;
options.path = u.path;
doRequest(options, function(response){
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
if (callback) callback(null, response, body);
});
}).on('error', function(e) {
console.log('error: %s', e.message);
if (callback) callback(e, null, null);
if (config.debug) {
console.log('Got error: ' + e.message);
console.log('Error: ' + util.inspect(e));
}
});
}
function post(inputUrl,options,postData,config,callback) {
console.log('post '+inputUrl);
var u = url.parse(inputUrl);
var proto = (u.protocol && u.protocol.startsWith('https')) ? https : http;
options.hostname = u.host;
options.port = u.port;
options.path = u.path;
options.method = 'post';
options.headers = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
};
var postReq = proto.request(options, function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function (data) {
body += data;
});
res.on('end', function(){
if (callback) callback(null, res, body);
});
}).on('error', function(e) {
console.log('error: %s', e.message);
if (callback) callback(e, null, null);
if (config.debug) {
console.log('Got error: ' + e.message);
console.log('Error: ' + util.inspect(e));
}
});
// post the data
postReq.write(postData);
postReq.end();
}
module.exports = {
get: get,
post: post
};