简体   繁体   中英

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
} 

Can be done way simpler in 2022:

var r = execSync("ifconfig");
console.log(r);

You will have to import like this:

const execSync = require("child_process").execSync;

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

In this case resulting value of the child_process will be in stdout. Why it hasn't worked for you? Also here

if(err) {
    console.log('shell error:'+stderr);
}

why are you checking for err and logging stderr ?

Your function looks asynchrone, so to get your response outside run_shell_command, you have to use a callback function like this :

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

run_shell_command(command, function (err, res) {
    if (err) {
        // Do something with your error
    }
    else {
        console.log(res);
    }
});

You also can simplify your run_shell_command function like this :

function run_shell_command(command, callback) {
    exec(command, callback);
}

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM