[英]nodejs callback exec result
我是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('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操作,我希望測試功能將返回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);
通過將錯誤詳細信息附加到“ ERROR”字符串,您還可以在結果數組中包括更多錯誤信息。
因此,您現在可以保存結果並使用curl進行查詢:curl http:// localhost:8081 / pingresults或可以實時執行curl http:// localhost:8081 / pingresultslive
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.