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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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).
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.