1

The code shown below is intended to output the present working directory to the console. Instead it outputs, "undefined". For purposes of this learning experience, it is important that I obtain the desired result as the returned value of the system function. Any ideas on how I can make this work?

#!/usr/bin/node
var child_process = require('child_process');
function system(cmd) {
  child_process.exec(cmd, function (error, stdout, stderr) {
  return stdout;
})};
console.log(system('pwd'));
Pang
  • 9,564
  • 146
  • 81
  • 122
user3311045
  • 689
  • 1
  • 7
  • 15
  • *"For purposes of this learning experience, it is important that I obtain the desired result as the returned value of the system function."* That's impossible. `child_process.exec` is an asynchronous process (that's why you have to pass a callback to it). For information why you get `undefined` (and how to solve that), see http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Felix Kling Sep 30 '15 at 00:47

1 Answers1

4

exec is executed asynchronously. Pass a callback to your function and you're set.

#!/usr/bin/node
var child_process = require('child_process');

function system(cmd, callback) {
  child_process.exec(cmd, function (error, stdout, stderr) {
     //You should handle error or pass it to the callback
     callback(stdout); 
  });
}

system('pwd', function(output){ 
  console.log(output); 
});

And here's how you would do it synchronously, which I believe is what you were looking for.

function systemSync(cmd) {
  return child_process.execSync(cmd).toString();
}

console.log(systemSync("pwd"));
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • Thanks. Works great. Actually I was looking for both the sync and the async way for doing it as I am having a bit of trouble getting my head wrapped around callbacks. So, your answer was most helpful. Thanks. – user3311045 Sep 30 '15 at 01:23