简体   繁体   English

Node.js函数输出到变量

[英]Node.js function output to variable

i have a grep function that i am using to seperate some data out. 我有一个grep函数,我正在使用它来分离出一些数据。

I ran into an issue, instead of outputting the data to the console, i need it to store it to a variable. 我遇到了一个问题,不是将数据输出到控制台,而是将其存储到变量中。

for example, here is my actual function. 例如,这是我的实际功能。

function funGrep(cmd,callback,search,args){
    exec(cmd,function(err,stdout){
        if(!stdout)
            return;
        var lines = stdout.toString().split(EOL);
        var re = new RegExp(search,args);
        for(var line in lines){
            var results = lines[line].match(re);
            if(results){
                for(var i = 0; i < results.length; i++){
                    callback(results[i]);
                }
            }
        }
    });
}

and here is my actual calling of the function into play. 这是我对该函数的实际调用。

funGrep("ping -n 3 google.com",console.log,"time=[0-9\.]+ ?ms");

instead of logging the output to the console, how can i just assign it to a variable like output. 而不是将输出记录到控制台,我如何才能将其分配给类似输出的变量。

thank you! 谢谢!

All you should have to do is create your own callback function that does whatever you need it to do with your data/results. 您需要做的就是创建自己的回调函数,该函数可以对数据/结果执行所需的任何操作。 It would look something like this: 它看起来像这样:

function theCallback (data) {
    ... do whatever you want with your data ...
}

And then instead of console.log, you would pass in this function as an argument. 然后,您可以传入此函数作为参数,而不是console.log。

funGrep("ping -n 3 google.com",theCallback,"time=[0-9\.]+ ?ms");

You could you the callback to append the data to a variable, and modify the callback to notify the handler when the function has finished: 您可以通过回调将数据追加到变量,然后修改回调以在函数完成后通知处理程序:

function funGrep(cmd,callback,search,args){
    exec(cmd,function(err,stdout){
        if(err){
            console.log(err);
            return;
        }
        if(!stdout)
            return;
        var lines = stdout.toString().split(EOL);
        var re = new RegExp(search,args);
        for(var line in lines){
            var results = lines[line].match(re);
            if(results){
                for(var i = 0; i < results.length; i++){
                    callback(results[i],false);
                }
            }
        }
        callback(null,true); //finsished
    });
}

var myData = [];
funGrep("ping -n 3 google.com",function(result,finished){if(!finished) myData.push(result); else goOn();},"time=[0-9\.]+ ms");

function goOn(){
    //funGrep finished
    console.log("Result: " + myData);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM