在if语句中使用child_process.exec的返回值?
我有这个function:
function checkfType(a,b){ exec("file '"+a+"'",function(err,stdout,stderr){ if(stdout.containsString(b)===true){return true}else{return false} }) }
但是,如果我在if语句中使用if(checkfType(".","directory"){}
,它只是变成“false”。我将exec
函数作为非函数进行testing,并使用它来代替if语句:
exec("file '.'",function(err,stdout,stderr){ if(stdout.containsString("directory")===true){ console.log("It works!); }else{ console.log("It doesn't work.";} });
这工作得很好。
我被引导认为exec
函数是asynchronous的(或类似的),这是我的问题所在。
有没有办法在if语句中使用exec
的输出?
有没有办法在if语句中使用
exec
的输出?
是的,但不是调用它的函数的返回值。
我被引导认为
exec
函数是asynchronous的(或类似的),这是我的问题所在。
对。 你的函数将需要接受一个callback函数,当exec
完成时它会传递该标志:
function checkfType(a,b,callback){ exec("file '"+a+"'",function(err,stdout,stderr){ callback(stdout.containsString("directory")); }) }
用法:
checkfType("whatever", "directory", function(flag) { if (flag) { // It's a directory } else { // It isn't } });