提问者:小点点

我有一个执行流问题,当nodejs的子进程


我想做一个函数,它接收一个字符串作为输入,然后返回一个字符串作为输出,但是由于响应延迟,我做不到

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}`);

共1个答案

匿名用户

这里发生的是,回调不是从上到下执行的。 这意味着console.log(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}`);

这些文档是https://nodejs.org/dist/last-v14.x/docs/api/child_process.html#child_process_child_process_execsync_command_options

您可以使用一个NPM包来帮助shell处理(如果您正在构建的话):https://github.com/shelljs/shelljs,它用一个更简单的API包装了许多子进程部分。