Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the returned value from the child_process.exec in javascript?

I tried the following code, it shows the res is undefined. How can I return the stdout?

function run_shell_command(command)
{
    var res
    exec(command, function(err,stdout,stderr){
     if(err) {
        console.log('shell error:'+stderr);
    } else {
        console.log('shell successful');
    }
    res = stdout
    // console.log(stdout)
    });
    return res
} 
like image 223
J.R. Avatar asked Dec 04 '17 09:12

J.R.


People also ask

What is Child_process spawn?

child_process.exec() : spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete. child_process.execFile() : similar to child_process.exec() except that it spawns the command directly without first spawning a shell by default.

How do I run an exec in node JS?

The exec() function in Node. js creates a new shell process and executes a command in that shell. The output of the command is kept in a buffer in memory, which you can accept via a callback function passed into exec() .

What is a Child_process module in node JS?

js allows single-threaded, non-blocking performance but running a single thread in a CPU cannot handle increasing workload hence the child_process module can be used to spawn child processes. The child processes communicate with each other using a built-in messaging system.


1 Answers

you can't get the return value except you use synchronous version of the exec function. if you are still hellbent on doing that, you should use a callback

function run_shell_command(command,cb) {   
    exec(command, function(err,stdout,stderr){
        if(err) {
          cb(stderr);
        } else {
          cb(stdout);
       }
   });
}

run_shell_command("ls", function (result) { 
   // handle errors here
} );

or you can wrap the exec call in a promise and use async await

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

async function run_shell_command(command) {
   let result;
   try {
     result = await execProm(command);
   } catch(ex) {
      result = ex;
   }
   if ( Error[Symbol.hasInstance](result) )
       return ;

   return result;
}


run_shell_command("ls").then( res => console.log(res) );
like image 84
0.sh Avatar answered Sep 30 '22 17:09

0.sh