dotslashlu
dotslashlu

Reputation: 3401

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.

Upvotes: 8

Views: 18879

Answers (4)

ttfreeman
ttfreeman

Reputation: 5533

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
}

Upvotes: 2

Tom
Tom

Reputation: 556

You can call exec with cwd param like so:

exec('ls -a', {
    cwd: '/Users/user'
}, (err, stdout) => {
    if (err) {
        console.log(err);           
    } else {
        console.log(stdout);
    }
})

But beware, cwd doesn't understand '~'. You can use process.env.HOME instead.

Upvotes: 0

anvarik
anvarik

Reputation: 6487

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

Upvotes: 1

Emil Condrea
Emil Condrea

Reputation: 9973

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

Upvotes: 18

Related Questions