0

I have this function:

getSlaves: function() {
  fs.readFile('/etc/hosts', function(err, data) {
    var array = data.toString().split("\n");
    for(i in array) {
      if (array[i].indexOf('slave') > -1){
        var workerNo = array[i].slice(-1);
        var ip = array[i].split(" ");
        console.log(ip);
      }
    }
  });
}

At present it writes this to console:

[ '192.168.11.1', 'slave1' ]
[ '192.168.11.2', 'slave2' ]
[ '192.168.11.3', 'slave3' ]

I want this to return so I can use it in another function. I've tried adding return(ip) and callback(ip) to the method but that doesn't work.How can I return these values so they can be used by an different function?

pac
  • 491
  • 1
  • 7
  • 30
  • have you tried declaring the variable outside of the function so that it is global, then setting it in the function? –  Mar 30 '18 at 13:24
  • You may also want to have [tag:javascript]. – user202729 Mar 30 '18 at 13:26
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – vibhor1997a Mar 30 '18 at 13:27
  • You need to build a list of `ip` values and return them all at once. Or use function generator and yield the values (<-- not sure if this is a good idea). – user202729 Mar 30 '18 at 13:27

1 Answers1

0

Way you can pass the array of ips into a callback

function getSlaves(callback) {
    if (err) {
        callback(err);
    }
    else {
        fs.readFile('/etc/hosts', function (err, data) {
            var array = data.toString().split("\n");
            let data = [];//to store ips
            for (i in array) {
                if (array[i].indexOf('slave') > -1) {
                    var workerNo = array[i].slice(-1);
                    var ip = array[i].split(" ");
                    data.push(ip);
                }
            }
            callback(undefined, rarr);
        });
    }
}

How do you access the array

function yourFunc(){
    getSlaves((err,data)=>{
        if(err){
            console.log(err);
        }
        else{
            console.log(data);
        }
    });
}
vibhor1997a
  • 2,336
  • 2
  • 17
  • 37