Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I make node child_process exec continuously

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.
like image 862
dotslashlu Avatar asked Jan 20 '13 17:01

dotslashlu


3 Answers

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

like image 133
Emil Condrea Avatar answered Oct 19 '22 21:10

Emil Condrea


You can use nodejs promisify and async/await:

const { promisify } = require('util');
const exec = promisify(require('child_process').exec);

export default async function () {
  const cpu = await exec('top -bn1');
  const disk = await exec('df -h');
  const memory = await exec('free -m');

  const payload = {
    cpu,
    disk,
    memory,
  };

 return payload
}
like image 42
ttfreeman Avatar answered Oct 19 '22 21:10

ttfreeman


If you want to use cd first, better use process.chdir('~/'). Then single exec() will do the job.

like image 39
anvarik Avatar answered Oct 19 '22 22:10

anvarik