如果我拨打“http://localhost:3000/?fqn=mfgthun.ch&port=80”,那么我会收到以下字符串:
{"source":"U259636","destination":"mfgthun.ch","ips":[]}
重新提交的内容应如下:
{"source":"U259636","destination":"mfgthun.ch","ips":[{"ip":"87.237.169.85","reachable":false}]}
函数Write
中的部分丢失了......我是否需要在此处添加另一个回调?或者还有其他解决方案吗?
为什么在第一个app.get
块完成之前不等待?
const express = require('express')
const app = express()
const isReachable = require('is-reachable');
var dns = require('dns');
var os = require('os');
var url = require('url');
var jsonResponse;
function Write (ipPort, ip) {
this.ipPort = ipPort;
this.ip = ip;
this.callback = function(reachable) {
var temp = {ip: ip, reachable: reachable };
global.jsonResponse.ips.push(temp);
};
}
app.get("/", function(httpRequest, httpResponse, next){
try {
var url_parts = url.parse(httpRequest.url, true);
var query = url_parts.query;
global.jsonResponse = { source: os.hostname(), destination: query.fqn, ips: [] };
dns.resolve4(query.fqn, function (err, addresses) {
if (err) throw err;
for(var i = 0; i < addresses.length; i++) {
var ipPort = addresses[i] + ':' + query.port;
var write = new Write(ipPort, addresses[i]);
isReachable(ipPort).then(write.callback);
};
});
} catch(err) {
console.log(err);
};
next();
});
app.get("/", function(httpRequest, httpResponse){
httpResponse.write(JSON.stringify(global.jsonResponse));
httpResponse.end();
});
app.listen(3000)