繁体   English   中英

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

[英]I have a execution flow problem whith nodejs child process

我想做一个 function 接收作为输入的字符串并将 output 作为字符串返回给我,但由于响应延迟,我无法做到

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

You could use a NPM package that helps with the shell handling if that's what you are building: https://github.com/shelljs/shelljs which wraps alot of the child process parts with an easier API.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM