how do I make node child_process exec continuously

dotslashlu picture dotslashlu · Jan 20, 2013 · Viewed 8.2k times · Source

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

I tried

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.

Answer

Emil Condrea picture Emil Condrea · Jan 21, 2013

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

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

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

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