/
httprequire.js
95 lines (64 loc) · 1.67 KB
/
httprequire.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Object is empty ?
var _isEmpty = function(o) { return ((o == null) || (o instanceof Array && o.length == 0) || (typeof(o) == "object" && Object.keys(o).length == 0)) };
var _cache = { };
// Run remote code
var _eval = function(data) {
var
module = { exports: {} };
(function(){
var
exports = {};
try {
eval(data);
}
catch(ex){
throw new Error("Exception evaluating remote code '"+data+"'");
}
if ( !_isEmpty(exports) && _isEmpty(module.exports) )
module.exports = exports;
})();
return module.exports;
};
// Syncronous require
var _syncRequire = function(url,force) {
if ( !force && _cache[url] != null )
return _cache[url];
var
httpsync = require('httpsync'),
req = httpsync.get({url: url}),
res = req.end(),
data = res.data.toString();
if ( !data ) {
console.log("Got no data. Status was: "+res.status);
return null;
}
// Eval the code
_cache[url] = _eval(data);
return _cache[url];
};
// Asyncronous require
var _asyncRequire = function(url,force,handler) {
if ( !force && _cache[url] != null )
return handler(_cache[url]);
var
http = require('http'),
data = '';
http.get(url, function(res) {
if ( res.statusCode != 200 )
return handler(null);
res.setEncoding('utf8');
res.on('data', function(chunk){ data += chunk; });
res.on('end', function(){
_cache[url] = _eval(data);
return handler(_cache[url]);
});
}).on('error',function(){handler(null);});
};
// Set global httprequire function
global.httprequire = function(url,force,handler) {
if ( typeof force == "function" ) {
handler = force;
force = false;
}
return handler ? _asyncRequire(url,force,handler) : _syncRequire(url,force);
};