我想制作一个函数,该函数接收作为输入的String并以字符串形式返回给我输出,但是由于响应延迟,我无法执行
var resultado = "old value";
function execShell(cmd) {
exec("uname", (error, data, getter) => {
if(error){
console.log("error",error.message);
return;
}
if(getter){
console.log("data",data);
return;
}
console.log(`need before exec: ${data}`);
resultado = data;
});
}
/* shell command for Linux */
execShell('uname');
console.log(`need after exec: ${resultado}`);
这里发生的是,没有从上到下执行回调。这意味着在子进程尚未返回console.log(need after exec: ${resultado});
之后立即调用execShell
。
您可以使用同步版本执行它:
const cp = require("child_process");
const result = cp.execSync("uname").toString(); // the .toString() is here to convert from the buffer to a string
console.log(`result after exec ${result}`);
如果您要构建的是NPM包,则可以使用它来帮助处理Shell:https://github.com/shelljs/shelljs,它使用更简单的API封装了许多子流程部件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句