5

I would like make this function return the result of the exec command in a var. How would I go about doing this?

// System Serial Number
function systemSerialNumber(response) {
  console.log("Request handler 'systemSerialNumber' was called.");
  exec("dmidecode -t 1 | grep 'Serial Number:' | cut -d: -f2 | sed -e 's/^[ \t]*//g'", function (error, stdout, stderr) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write(stdout);
    response.end();
  });
}
maerics
  • 151,642
  • 46
  • 269
  • 291
  • 1
    The formatting on your source is fairly poor, so you technically have the first function (which I'm assuming is the function you're talking about) commented out. What you're asking for, though, is to turn this async call into a synchronous one, which is a bad idea on a [cooperatively scheduled](http://en.wikipedia.org/wiki/Cooperative_Scheduler#Cooperative_multitasking.2Ftime-sharing) event system like Node.js. I think you need to rethink your intended API. –  Feb 16 '12 at 22:38

2 Answers2

1

From http://nodejs.org/docs/v0.3.1/api/all.html#child_process.exec describes how to get the output of a command asynchronously. But it sounds like you want to get the results synchronously so you can return them, in which case, you're probably more interested in this SO question: node.js execute system command synchronously

Community
  • 1
  • 1
broofa
  • 37,461
  • 11
  • 73
  • 73
0

I would suggest using a library such as Step https://github.com/creationix/step

function systemSerialNumber(response) {
  var output = "";
  Step(
    function runCommand() {
      exec("dmidecode -t 1 | grep 'Serial Number:' | cut -d: -f2 | sed -e 's/^[ \t]*//g'", this);
    },
    function(error, stdout, stderr) {
      output = stdout;
      response.writeHead(200, {"Content-Type": "text/plain"}); response.write(stdout); response.end();
  });
return output;
}
Dave Kasper
  • 1,369
  • 1
  • 11
  • 18