我有 nodejs 子进程的执行流程问题

I have a execution flow problem whith nodejs child process

我想创建一个函数来接收作为输入的字符串,returns我作为字符串输出,但由于响应延迟我无法做到

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

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

如果您要构建的是 shell 处理,您可以使用 NPM 包来帮助处理:https://github.com/shelljs/shelljs 它用更简单的 API 包装了很多子进程部分。