Node.js nodejs回调执行结果
我不熟悉node,在异步回调方面遇到了一些麻烦 我正在编写一个脚本来ping服务器列表,如果所有主机都可以ping,我希望返回一个状态为“OK”的数组Node.js nodejs回调执行结果,node.js,callback,exec,ping,Node.js,Callback,Exec,Ping,我不熟悉node,在异步回调方面遇到了一些麻烦 我正在编写一个脚本来ping服务器列表,如果所有主机都可以ping,我希望返回一个状态为“OK”的数组 hostaddr = [ '10.102.14.20', '10.102.14.21', '10.102.14.22' ]; pingstat = testping(hostaddr, function(err, callback) { console.log(callback); }); const exec = require('
hostaddr = [ '10.102.14.20', '10.102.14.21', '10.102.14.22' ];
pingstat = testping(hostaddr, function(err, callback) {
console.log(callback);
});
const exec = require('child_process').exec;
var testping = function(hostaddr,callback) {
var pingstat = [];
for (let i = 0; i < hostaddr.length; i++) {
const child = exec('ping -c 1 ' + hostaddr[i],
(error, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
} else {
pingstat.push("OK");
callback(pingstat);
}
});
}
}
如果所有主机的ping成功,我希望testping函数将返回pingstat['OK','OK','OK'],但我的代码不起作用,请提供帮助,我将尝试以下操作:
const exec = require('child_process').exec;
var testping = function(hostaddr,callback) {
var pingstat = [];
for (let i = 0; i < hostaddr.length; i++) {
const child = exec('ping -c 1 ' + hostaddr[i],
(error, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
pingstat.push("ERROR");
} else {
pingstat.push("OK");
}
if (pingstat.length == hostaddr.length) {
callback (pingstat);
}
});
}
}
var hostaddr = [ '10.102.14.20', '10.102.14.21', '10.102.14.22' ];
var pingResults = null;
var hostaddr = [ '192.168.2.54' ,'192.168.2.541'];
testping(hostaddr, function(results) {
console.log("Ping results: " + results);
// Save results.
pingResults = results;
});
var express = require('express');
var app = express();
app.get('/pingResults', function(req, res, next) {
res.status(200);
res.header("Content-Type", "application/json");
res.end(JSON.stringify({pingResults: pingResults}));
});
app.get('/pingresultslive', function(req, res, next) {
testping(hostaddr, function(results) {
console.log("Ping results: " + results);
res.status(200);
res.header("Content-Type", "application/json");
res.end(JSON.stringify({pingResults: pingResults}));
});
});
var httpPort = 8081;
console.log('Listening on port: ' + httpPort);
app.listen(httpPort);
通过将错误详细信息附加到错误字符串,还可以在结果数组中包含更多错误信息
因此,现在可以使用curl保存结果和查询:
卷曲
或者你可以现场表演
curl我实际上想将pingstat打印到我的html中,你能给我更多关于如何将pingstat存储为数组的提示吗,这样我以后可以使用res.endpingstat打印它,而不是登录到控制台。我现在更新了答案,以包括res.end部分!我可以记录正确的“Ping结果:OK,OK,OK”,但是html只接收null。不知道为什么结果没有正确地传递到HTML你是如何更新你的HTML的,你是在调用node.js webservice还是在客户端上这样做,例如在页面中嵌入JavaScript?好的,很酷,所以你需要在回调方法本身中更新HTML DOM。e、 g testpinghostaddr,functionresults{console.logPing results:+results;//保存结果。pingResults=results;};