nodejs回调exec结果

时间:2018-01-26 06:40:01

标签: node.js callback exec ping

我是节点新手,并且遇到了一些令人头疼的异步回调。

我正在编写一个脚本来ping服务器列表,并希望返回一个数组来表示其状态(如果所有主机都是'pingable',则为'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);
                }
            });
    }
}

我希望测试功能将返回pingstat ['确定,'确定','确定']如果所有主机ping成功,但我的代码不起作用,请帮助

1 个答案:

答案 0 :(得分:1)

我会尝试这样的事情:

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保存结果和查询:     卷曲http://localhost:8081/pingresults 或者你可以现场直播     卷曲http://localhost:8081/pingresultslive