-
Notifications
You must be signed in to change notification settings - Fork 50
/
nodemain.js
114 lines (99 loc) · 3.14 KB
/
nodemain.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* Created by leon.li on 2015/5/4.
*/
var easyProxy = require("./lib/easyproxy.js");
var findHost = require("./lib/findhost.js");
var dirname = require('./lib/util').dirname;
var platform = require("./lib/platform");
var dns = require('dns');
var path = require('path');
//var execPath = path.dirname( process.execPath );
var CONFIG = {
"hostFilePath": null,
"chromePath": null,
"systemHostFilePath": platform.systemHostFilePath,
"serverPort": 9393
}
function setConfig(name, value) {
CONFIG[name] = value;
}
function startNode() {
var logger = global.window.logger;
// var gui = global.window.nwDispatcher.requireNwGui();
// var hostPath = path.join( gui.App.dataPath , './hosts');
logger.doLog("log", "node代码启动成功,端口:" + ( global.window.localStorage.getItem("serverPort") || 9393 ));
var nwProxy = new easyProxy({
port: global.window.localStorage.getItem("serverPort") || 9393,
onBeforeRequest: function(req) {
try {
var host = findHost(global.window.__hostState, req.host);
var sysTemHost = findHost(CONFIG.systemHostFilePath, req.host);
if (host) {
logger.doLog("log", req.host + "被代理到:" + host);
req.host = host;
req.replace = true;
}
if (sysTemHost && !host) {
req.needDnsResolve = true;
}
}
catch(e) {
logger.doLog("error", e.message);
}
},
onServerError: function(e) {
logger.doLog("error", "serverError" + e.message);
},
onRequestError: function(e) {
console.log(e.message);
}
});
nwProxy.start();
}
var _cache = {};
function logHost( adress, ip, text, level ) {
level = level || "log";
if (!_cache[adress + level]) {
_cache[adress + level] = [logInfo(level, adress + text + ip), 1];
}
else {
_cache[adress + level][1] += 1;
_cache[adress + level][0].innerHTML = '<i class="times">' + _cache[adress + level][1] + '</i>' + adress + text + ip;
}
}
function logInfo(level, text) {
var logWrapper = global.window.document.getElementById("log_area");
var p = global.window.document.createElement('p');
p.className = level;
p.innerHTML = text;
logWrapper.appendChild(p);
return p;
}
function dnsTest(host) {
if (typeof host != "string") {
return;
}
dns.lookup(host, function onLookup(err, addresses, family) {
if (err) {
return;
}
var ip = addresses;
dns.resolve(host, function onLookup(err, addresses, family) {
if (err) {
return;
}
var bool = true;
addresses.forEach(function (item){
if (item == ip) {
bool = false;
return;
}
});
bool && logHost(host, ip, "被检测到可能配置了系统host:", "warn");
});
});
}
module.exports = {
start: startNode,
setConfig: setConfig
}