1

I have this function:

function checkfType(a,b){
  exec("file '"+a+"'",function(err,stdout,stderr){
    if(stdout.containsString(b)===true){return true}else{return false}
  })
}

However, if I use it in an if statement like this: if(checkfType(".","directory"){}, it just goes "false". I tested the exec function as a non-function and using it instead of the if statement:

exec("file '.'",function(err,stdout,stderr){
  if(stdout.containsString("directory")===true){
    console.log("It works!);
  }else{
    console.log("It doesn't work.";}
});

Which works just fine.

I am led to believe tha the exec function is async (or similar), which is where my problem lies.

Is there any way to use exec's output in an if statement?

Jacob Pedersen
  • 347
  • 2
  • 4
  • 12
  • Assuming `containsString` returns `true` or `false`, `if(stdout.containsString(b)===true){return true}else{return false}` is a *really* long-winded way to write `return stdout.containsString(b);` If it may return something truthy that you don't want to consider `true` (as your statement filters out other truthy values), it's a long way to write `return stdout.containsString(b)===true;` – T.J. Crowder Jul 11 '14 at 12:33

1 Answers1

1

Is there any way to use exec's output in an if statement?

Yes, but not as a return value for the function calling it.

I am led to believe that the exec function is async (or similar), which is where my problem lies.

Right. Your function will need to accept a callback that it will pass the flag to when the exec completes:

function checkfType(a,b,callback){
  exec("file '"+a+"'",function(err,stdout,stderr){
    callback(stdout.containsString("directory"));
  })
}

Usage:

checkfType("whatever", "directory", function(flag) {
  if (flag) {
    // It's a directory
  } else {
    // It isn't
  }
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks for the quick answer! Is my best option then to wrap the `exec` function in another function (to not make my code a mess), and use it instead of an if statement? – Jacob Pedersen Jul 11 '14 at 12:32
  • @JacobPedersen: That doesn't change anything, then you'd just have to have *that* function accept a callback. You *cannot* convert an asynchronous result into a function's return value. – T.J. Crowder Jul 11 '14 at 12:34
  • 1
    I see your edit, I think I understand async callbacks now, thanks. By "wrapping", I meant something similar to what you did in your edit. – Jacob Pedersen Jul 11 '14 at 12:35