13

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
} 
J.R.
  • 769
  • 2
  • 10
  • 25

4 Answers4

16

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) );
0.sh
  • 2,659
  • 16
  • 37
5

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;
Christian
  • 4,902
  • 4
  • 24
  • 42
Devtools
  • 49
  • 1
  • 1
  • 1
    `console.log(r)` returns the result as bytecode. Use `console.log(r.to String())` to get a human-readable result. – equiman May 17 '22 at 17:17
  • beware of whitespace (might not notice them in the console). add `..trim()` to remove them. `console.log(r.to String().trim())` – kevinunger Jan 30 '23 at 00:01
  • You don't need to call `.toString`. The default encoding is 'buffer'. Use 'utf8' in the options argument for execSync, e.g. `execSync('ls', { encoding: 'utf8' })`. See https://nodejs.org/api/child_process.html#child_processexecsynccommand-options – joematune Jul 03 '23 at 15:32
2

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.

Sparw
  • 2,688
  • 1
  • 15
  • 34
0

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?

Polski Max
  • 66
  • 2
  • -.- I have not idea.....I printed the res inside the funtion(err, stdout, stderr){}. It shows everything is good. Then I printed the res inside the run_shell_command, it shows undefined -.- seems exiting the exec function made everything different – J.R. Dec 04 '17 at 09:10
  • Try to add check for stderr e.g. : `if (stderr) { console.log(stderr) } – Polski Max Dec 04 '17 at 09:12