0

Hi so I have been using node-cmd(https://www.npmjs.com/package/node-cmd) to run some simple command like 'dir' etc and I would like to use the output outside of the function or store somewhere. I tried just storing it as a variable but it does not work. Hope someone can shed some light on this. Thanks!

var files="";

cmd.get('dir /b /a-d',function(err, data, stderr){

            if(err){
                console.log(err);
            }

            else {

                console.log(data);
                files = data;

            }
        });

console.log(files);
JWH_
  • 267
  • 2
  • 12
  • 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 Dec 30 '17 at 08:14

1 Answers1

2

Remember cmd is an async call.
You test console.log(files) too early: data are not here at this moment.
The good way is to call back not an in function, but the function you want to have for using the answer. Hth

pirela
  • 498
  • 6
  • 15
  • Thanks! I think I get the idea but I wasn't able to figure out how to split the cmd command's and the callback function itself. So in general I will have to create a callback function and call the callback function at a certain point? – JWH_ Dec 30 '17 at 08:57
  • 1
    It is the cmd.get that will call back the function you designed inside the call. Your code works but you cannot use the data in files before cmd.get call back the function. To see that, try a loop with some wait around your Console.log(files). – pirela Dec 30 '17 at 09:16
  • Another way is to call in a sync manner. See node sync. But you ll break the node philosophy. In my opinion can be used only in an init part of a prog – pirela Dec 30 '17 at 09:25