简体   繁体   English

Node.js 同步 shell exec

[英]Node.js synchronous shell exec

I am having a problem with async shell executes in node.js.我在 node.js 中执行异步 shell 时遇到问题。

In my case, node.js is installed on a Linux operating system on a raspberry pi.就我而言,node.js 安装在树莓派上的 Linux 操作系统上。 I want to fill an array with values that are parsed from a shell script which is called on the pi.我想用从 pi 上调用的 shell 脚本解析的值填充数组。 This works fine, however, the exec() function is called asynchronously.这工作正常,但是 exec() 函数是异步调用的。

I need the function to be absolute synchron to avoid messing up my whole system.我需要该功能是绝对同步的,以避免弄乱我的整个系统。 Is there any way to achieve this?有没有办法实现这一目标? Currently I am trying a lib called .exe, but the code still seems to behave asynchron.目前我正在尝试一个名为 .exe 的库,但代码似乎仍然表现异步。

Here's my code:这是我的代码:

function execute(cmd, cb)
{
  child = exec(cmd, function(error, stdout, stderr)
  {
    cb(stdout, stderr);
  });
}



function chooseGroup()
{
  var groups = [];

  execute("bash /home/pi/scripts/group_show.sh", function(stdout, stderr)
  {
    groups_str  = stdout;
    groups      = groups_str.split("\n");
  });

  return groups;
}


//Test
console.log(chooseGroup());

If what you're using is child_process.exec , it is asynchronous already.如果您使用的是child_process.exec ,则它已经是异步的。

Your chooseGroup() function will not work properly because it is asynchronous.您的chooseGroup()函数将无法正常工作,因为它是异步的。 The groups variable will always be empty. groups变量将始终为空。

Your chooseGroup() function can work if you change it like this:如果您像这样更改它,您的chooseGroup()函数可以工作:

function chooseGroup() {    
  execute("bash /home/pi/scripts/group_show.sh", function(stdout, stderr) {
    var groups = stdout.split("\n");
    // put the code here that uses groups
    console.log(groups);
  });
}

// you cannot use groups here because the result is obtained asynchronously
// and thus is not yet available here.

If, for some reason, you're looking for a synchronous version of .exec() , there is child_process.execSync() though it is rarely recommended in server-based code because it is blocking and thus blocks execution of other things in node.js while it is running.如果出于某种原因,您正在寻找.exec()的同步版本,则可以使用child_process.execSync()尽管在基于服务器的代码中很少推荐它,因为它会阻塞并因此阻止节点中其他事物的执行.js 在运行时。

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

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