如何使正常功能在 node.js 中返回

How to make normal function to be returning in node.js

    function puts(error, stdout, stderr) {
    if (error) {
        console.log("error", "Error connecting");
        result = "Failed";
        console.log(result)
    }
    else {
        sys.puts(stdout)
        result = "Success"
        console.log(result)
    }
    }

//The calling function is mentioned as below:
app.get('/api/platforms1', function(req, res){
    exec("ping localhost",puts);
});

//我正在工作 stack.I 已经创建了一个方法来 ping ip 地址并显示他们的 result.But 现在我想将结果显示为 return function.How 我们能做到吗??

首先sysdeprecated你可以用util代替它。

如果您想在任何地方获得结果,您可以用 callback 来做,因为 Node.js 本质是异步的。

第一个:

在windows中,如果你使用:

ping google.com

你只会得到 4 条信息 ping,但是在 Ubuntu 上,如果你使用那个命令,只有你用 Ctrl+C 停止它才能停止 ping。

要解决这个问题,我们需要使用 -c 标志。 -c 选项告诉 ping 程序在发送(或接收)指定数量的 ECHO_RESPONSE 数据包后停止。

第二个:

您需要使用 res.send 发送回 ping 响应,但由于您的 callback 功能,即 puts 您无权访问resreq.

使用此包装器函数传递您要通过回调访问的另一个参数

function execute(command, callback, res) {
    exec(command, function(error, stdout, stderr) {
        // Notice extra params I have passed here^,  ^
        callback(error, stdout, stderr, res);
    });
}

您可以将其用作

    execute("ping -c 2 google.com", puts, /*pass extra params*/ res);

并在您的 callback 函数之后捕获额外的参数

                                    || 
                         ---------- \/

function execute(command, callback, res) {
  ...
}

完整代码:

var exec = require('child_process').exec;

function puts(error, stdout, stderr, res) {
        // Notice extra params here  ^
    if (error) {
        console.log("error", "Error connecting");
        result = "Failed";
        console.log(result)
    } else {
        sys.puts(stdout)
        result = "Success"
        console.log(result)
        //send response to client
        res.send(result)
    }
}

//The calling function is mentioned as below:
app.get('/api/platforms1', function(req, res) {
    execute("ping -c 1 google.com", puts, /*pass extra params*/ res);
});

function execute(command, callback, res) {
    exec(command, function(error, stdout, stderr) {
        // Notice extra params I have passed here^,  ^
        callback(error, stdout, stderr, res);
    });
}

参考:

https://askubuntu.com/questions/200989/ping-for-4-times

Get the output of a shell command in node.js