如何使节点child_process连续执行 [英] how do I make node child_process exec continuously

查看:390
本文介绍了如何使节点child_process连续执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何连续 exec ?例如 cd 后的 ls 吗?

How to exec continuously? e.g. ls after cd?

我尝试过

exec = require('child_process').exec;
exec('cd ~/', 
  function(){
    exec('ls'),
    function(err, stdout, stderr){
      console.log(stdout); // this logs current dir but not ~/'s
    }
  }
)

exec('cd ~/').exec('ls', function(err, stdout, stderr){
  console.log(stdout);
})//this also fails because first exec returns a ChildProcess Object but not itself.


推荐答案

无法执行此操作,因为exec和spawn创建一个新的过程。但是有一种方法可以模拟这种情况。您可以使用exec启动一个进程并同时执行多个命令:
在命令行中,如果要在同一行执行3个命令,则应编写:

It is not possible to do this because exec and spawn creates a new process. But there is a way to simulate this. You can start a process with exec and execute multiple commands in the same time: In the command line if you want to execute 3 commands on the same line you would write:

cmd1 & cmd2 & cmd3

因此,所有3条命令都在同一进程中运行,并且可以访问由前一个命令修改的上下文执行的命令。
让我们举一个例子,您要执行cd ../,然后执行dir并查看上一个目录列表。
您应该在cmd中写:

So, all 3 commands run in the same process and have access to the context modified by the previous executed commands. Let's take your example, you want to execute cd ../ and after that to execute dir and to view the previous directory list. In cmd you shoud write:

cd../ & dir

从节点js中,您可以使用exec启动一个进程,并告诉它启动另一个节点实例,将评估内联脚本:

From node js you can start a process with exec and to tell it to start another node instance that will evaluate an inline script:

var exec = require('child_process').exec;
var script = "var exec = require('child_process').exec;exec('dir',function(e,d,er){console.log(d);});";
script = '"'+script+'"';//enclose the inline script with "" because it contains spaces
var cmd2 = 'node -e '+script;
var cd = exec('cd ../ &'+cmd2,function(err,stdout,strerr)
{
    console.log(stdout);//this would work
})

如果您只想更改当前目录,则应查阅有关文档 http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

If you just want to change the current directory you should check the documentation about it http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

这篇关于如何使节点child_process连续执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆