简体   繁体   中英

Node.js function output to variable

i have a grep function that i am using to seperate some data out.

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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